这是我的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>
答案 0 :(得分:23)
您可以使用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);
答案 1 :(得分:-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;
}
}
}
看,你能找到一些东西