2

I found great information about traversing up the dom getting the node from a clicked element...

Traversing up the DOM getting the node from a clicked element

Who can help me to include in the breadcrumb the id= and class= attributes like you see in most buggers?

so instead of:

HTML  > BODY  > UL  > LI  > SPAN

I would like:

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

...or something similar.

J Alan
  • 77
  • 1
  • 11
Stone Pentecost
  • 270
  • 1
  • 2
  • 11

1 Answers1

1

Adding to the linked code, the code below will append all ids and classes on the element.

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

would output 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);
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
  • Thanks alot!! It works very good! can you help me also generatring this path? /html[1]/body[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div/div for use with php xpath? – Stone Pentecost Mar 18 '19 at 01:44