我想在给定元素之前放置一个新的节点元素。我正在使用insertBefore,但没有成功!
这是代码,
<DIV id="maindiv">
<!-- I would like to place the new element here -->
<DIV id="child1">
<IMG />
<SPAN />
</DIV>
<DIV id="child2">
<IMG />
<SPAN />
</DIV>
//$div is a new div node element,
//The code I'm trying, is the following:
$maindiv->item(0)->parentNode->insertBefore( $div, $maindiv->item(0) );
//Obs: This code asctually places the new node, before maindiv
//$maindiv object(DOMNodeList)[5], from getElementsByTagName( 'div' )
//echo $maindiv->item(0)->nodeName gives 'div'
//echo $maindiv->item(0)->nodeValue gives the correct data on that div 'some random text'
//this code actuall places the new $div element, before <DIV id="maindiv>
感谢任何形式的帮助,谢谢!
答案 0 :(得分:5)
如果maindiv来自getElementsByTagName()
,则$maindiv->item(0)
是id = maindiv的div。所以你的代码工作正常,因为你要求它在maindiv之前放置新的div。
为了让它像你想要的那样工作,你需要得到maindiv的孩子们:
$dom = new DOMDocument();
$dom->load($yoursrc);
$maindiv = $dom->getElementById('maindiv');
$items = $maindiv->getElementsByTagName('DIV');
$items->item(0)->parentNode->insertBefore($div, $items->item(0));
请注意,如果您没有DTD,PHP不会返回任何带有getElementsById的内容。要使getElementsById起作用,您需要拥有DTD或指定哪些属性是ID:
foreach ($dom->getElementsByTagName('DIV') as $node) {
$node->setIdAttribute('id', true);
}
答案 1 :(得分:0)
找到解决方案,
$child = $maindiv->item(0);
$child->insertBefore( $div, $child->firstChild );
我不知道这有多大意义,但很好,有效。
答案 2 :(得分:0)
从头开始,这似乎也有效:
$str = '<DIV id="maindiv">Here is text<DIV id="child1"><IMG /><SPAN /></DIV><DIV id="child2"><IMG /><SPAN /></DIV></DIV>';
$doc = new DOMDocument();
$doc->loadHTML($str);
$divs = $doc->getElementsByTagName("div");
$divs->item(0)->appendChild($doc->createElement("div", "here is some content"));
print_r($divs->item(0)->nodeValue);