简体   繁体   English

遍历 dom 从带有 id 和 class 的单击元素中获取

[英]Traversing up the dom getting the from a clicked element with id and class

I found great information about traversing up the dom getting the node from a clicked element...我发现了有关遍历 dom 以从单击的元素获取节点的重要信息...

Traversing up the DOM getting the node from a clicked element 遍历 DOM 从单击的元素中获取节点

Who can help me to include in the breadcrumb the id= and class= attributes like you see in most buggers?谁能帮助我在面包屑中包含 id= 和 class= 属性,就像您在大多数 bugger 中看到的那样?

so instead of:所以而不是:

HTML  > BODY  > UL  > LI  > SPAN

I would like:我想:

HTML  > BODY  > UL.menu  > LI  > SPAN#whatever

...or something similar. ...或类似的东西。

Adding to the linked code , the code below will append all ids and classes on the element.添加到链接代码,下面的代码将在元素上附加所有 id 和类。

Clicking an element <div id="id1" class="class1 class2">Test</div> ...单击元素<div id="id1" class="class1 class2">Test</div> ...

would output HTML > BODY > DIV#id1.class1.class2将输出HTML > BODY > DIV#id1.class1.class2

function clickHandler(event) {
    var target = event.target,
    breadcrumb = [];

    while (target) {
        var id = target.id;
        var classes = target.className;
        var crumb = target.tagName;
        if (id) { 
            crumb += "#" + id; 
        }
        if (classes) {
            var classList = classes.split(' ');
            for (var c = 0; c < classList.length; c++) {
                crumb += "." + classList[c];
            }
        }
        breadcrumb.unshift(crumb);
        target = target.parentElement;
    }
    console.log(breadcrumb.join(" > "));
}

document.addEventListener('click', clickHandler, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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