如有HTML情况如下
1:
<div id="div1"></div>
<div>123</div>2:
<div id="div1"></div>
<span></span>
<div>123</div>
-----------
现在要在div1里定义到他后面的那个div
我用
document.getElementById("div1").nextSibling在第一种情况OK,第二种不行
我查看文档说:Retrieves a reference to the next child of the parent for the object(定位同级下一对像)
那要如何来写才正确呢?谢谢

解决方案 »

  1.   

    var el=document.getElementById("div1");n;
    while(n=n.nextSilibling && n.nodeName!="DIV");
      

  2.   

    var el=document.getElementById("div1"),n=el;
    while(n=n.nextSilibling && n.nodeName!="DIV");
      

  3.   

    L@_@K<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title> new document </title>
      <meta name="generator" content="editplus" />
      <meta name="author" content="" />
      <meta name="keywords" content="" />
      <meta name="description" content="" />
     </head> <body>
    <div id="div1"> </div> 
    <span> </span> 
    <div>123 </div>
      <script type="text/javascript">
      <!--var nextDiv = GetNextSiblingByTagName(document.getElementById("div1"), "div");
    alert(nextDiv.innerText);function GetNextSiblingByTagName(source, tagName) {
    var target = source.nextSibling;
    while (target) {
    if (target.nodeType === 1 
    && target.tagName.toLowerCase() === tagName.toLowerCase()) {
    return target;
    }
    target = target.nextSibling;
    }
    }  //-->
      </script>
     </body>
    </html>
      

  4.   

    var el=document.getElementById("div1"),n=el.nextSibling;
    while(n.nodeName && n.nodeName!="DIV"){n=n.nextSibling}
    alert(n.innerHTML)