开发者

Append and prepend text nodes to a HTML element using DOM?

Here is my HTML code

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

How can I use DOM to append and prepend text nodes to the BODY elements without hurting its siblings?

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

like this

<html> 
    <body>
        Newly prepended text
        <div>开发者_如何转开发;A sample block <div>and child block</div></div>
        Newly appended text    
    </body>
</html>  


You can create text nodes with DOMText (or by using 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');

Now, appending is just:

$body->appendChild($after);

For prepending, we can use DOMNode::firstChild to get the first child of the body and DOMNode::insertBefore:

$body->insertBefore($before, $body->firstChild);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜