我想在给定元素之前放置一个新的节点元素。我在用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>

http://pastie.org/1070788
感谢您的帮助,谢谢!

最佳答案

如果maindiv来自getElementsByTagName(),则$maindiv->item(0)是id=maindiv的div。所以您的代码工作正常,因为您要求它将新的div放在maindiv之前。
为了让它像你想要的那样工作,你需要让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);
}

07-25 23:00