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

it's my code from add's and remove file input

<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>

and this 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;
        }
    }
}

Look can you find for yourself that something

于 2010-12-25T11:08:52.827 回答