17

これが私のHTMLコードです

<html> 
    <body>
        <div>A sample block <div>and child block</div></div>    
    </body>
</html>

DOMを使用して、兄弟を傷つけることなくテキストノードをBODY要素に追加および追加するにはどうすればよいですか?

$dom = new DOMdocument();    
@$dom->loadHTML($html);    
$xpath = new DOMXPath($dom);    
$body = $xpath->query('//body')->item(0);    

このような

<html> 
    <body>
        Newly prepended text
        <div>A sample block <div>and child block</div></div>
        Newly appended text    
    </body>
</html>  
4

2 に答える 2

24

DOMText次のコマンドを使用して(またはを使用してDOMDocument::createTextNode)テキストノードを作成できます。

$before = new DOMText('Newly prepended text');
// $before = $dom->createTextNode('Newly prepended text');
$after = new DOMText('Newly appended text');
// $after = $dom->createTextNode('Newly appended text');

さて、追加はただです:

$body->appendChild($after);

DOMNode::firstChild接頭辞として、体の最初の子を取得するために使用できますDOMNode::insertBefore

$body->insertBefore($before, $body->firstChild);
于 2010-12-25T11:12:36.100 に答える
-1

これは、ファイル入力の追加と削除からの私のコードです

<span class="file_box"><span><input class="text" type="text" name="emails[]" value="" /><br /></span></span><div style="padding: 0 0 5px 160px;">
                        <input type="button" class="add" value="+" style="width: 25px; height: 25px; margin: 0 5px 0 0;" onclick="addFile(this);" /><input type="button" class="drop" value="-" style="width: 25px; height: 25px;" onclick="dropFile(this);" disabled="true" />
                    </div>

そしてこのjs

var FileCount = 1;

function addFile(object){
    if(document.getElementById) {
        var el = object.parentNode.previousSibling.firstChild;
        var newel = el.parentNode.appendChild(el.cloneNode(true));
        newel.style.marginLeft = "160px";
        FileCount++;
        if(FileCount > 1){
            object.nextSibling.disabled = false;
        }
    }
}

function dropFile(object){
    if(document.getElementById) {
        var el = object.parentNode.previousSibling.lastChild;
        el.parentNode.removeChild(el);
        FileCount--;
        if(FileCount == 1){
            object.disabled = true;
        }
    }
}

あなたは自分自身のために何かを見つけることができますか

于 2010-12-25T11:08:52.827 に答える