简体   繁体   中英

How to get outermost parent node of inner child in plain JavaScript?

I got stuck in a problem, I wish to write a script that can show all the div ids of an inner div, for example:

<body id="bd">
<div id="canvas">
    <div id="nd1">
        <div>
            My text
        </div>
    </div>
    <div id="nd2">
        <div id="hd">Some Text</div>
    <div>
<div>

What I want is suppose when I click on div with no ID defined inside "nd1", I should get its parent div (ie nd1), and the outermost parent, kind of thing I want.

try

var allChildNodes = document.querySelectorAll("#nd1 div");
nodes = Array.prototype.slice.call(allChildNodes ,0); 
nodes.forEach(function(node){ 
   node.addEventListener("click", function(){
     console.log("Outer parent" + node.parentNode.outerHTML);
     console.log("Outermost parent" + node.parentNode.parentNode.outerHTML);
   });
});

To get the array of parent divs

var allChildNodes = document.querySelectorAll("#nd1 div");
nodes = Array.prototype.slice.call(allChildNodes ,0); 
nodes.forEach(function(node){ 
   node.addEventListener("click", function(){
     var parentDivs = [];
     while( !node.parentNode )
     {
        parentDivs.push(node.parentNode);
        node = node.parentNode;
     }
     console.log("parents" + parentDivs);
   });
});

For matching multiple divs starting from a specific string

var allChildNodes = document.querySelectorAll("[id^='nd'] div");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM