打印parentNode直到body

时间:2015-01-26 16:22:03

标签: javascript arrays

我有这段代码:

<body onMouseDown="javaScript:mouseEventHandler(event);">
   <div id="hello">
        <table>
            <tr>
                <td>Hi friends</td>
            </tr>
        </table>
   </div>
   <div id="result">
    <ul id="ularraydom">
    </ul>
   </div>

我需要进入一个名为result的新div,就像我展示的那样,是一个td的parentNodes数组,直到我得到BODY。

结果应该是这样的:

<ul id="ularraydom">
<li>TD</li> 
<li>TR</li> 
<li>TABLE</li> 
<li>DIV</li> 
<li>BODY</li>
</ul>

我尝试过:

function mouseEventHandler(mEvent)
{
  // Internet Explorer
 if (mEvent.srcElement)
   {
    alert(mEvent.srcElement.nodeName);
   }
 // Netscape and Firefox
 else if (mEvent.target)
   {
    var ularraydom = document.getElementById("ularraydom");
    ularraydom.innerHTML = "<li>" + mEvent.target.parentNode.nodeName; + "</li>";
    }
}

2 个答案:

答案 0 :(得分:1)

递归是你的朋友:

function printNode(node){
  var ularraydom = document.getElementById("ularraydom");
  ularraydom.innerHTML += "<li>" + node.nodeName; + "</li>"; // be aware of the += !

  if(node.nodeName !== "BODY"){
    printNode(node.parentNode); //recursion!
  }
}
<body>
   <div id="hello">
        <table>
            <tr>
                <td onclick="printNode(this)">click here</td>
            </tr>
        </table>
   </div>
   <div id="result">
    <ul id="ularraydom">
    </ul>
   </div>
</body>

答案 1 :(得分:0)

向上遍历非常简单:

var node = mEvent.target.parentNode;
while (node && node.nodeName !== 'HTML') {
    // print node.nodeName ...

    node = node.parentNode; // up
}