0

I would like to have a code that when finds a certain word it prints out the path from the uppermost node to the one containing this word. I have this code, but it repeats each element several times which is not what I need.. for example, instead of 'a -> a -> b -b - b -> c, I just ned a -> b -> c. This is a "working" snippet.

const allElements = document.body.querySelectorAll('*');
let path = '';
const word = "killed";
let elem;
for (let i = 0; i < allElements.length; i++) {
  const cur = allElements[i].cloneNode(true); 
  while (cur.lastElementChild) {
    cur.removeChild(cur.lastElementChild);
    path += cur.className + '-> '
  }
  if (cur.textContent.includes(word)) {
    elem = cur;
    break;
  }
}

console.log(path);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="grandpa">
  <div class="parent1">
    <div class="son1">
      <p class="p1">I like oranges</p>
    </div>
    <div class="son2">
      <p class="p1">yeeeey</p>
      <p class="p2">wohoo it's saturday</p>
    </div>
    <div class="son3"></div>
  </div>
  <div class="parent2"></div>
  <div class="parent3">
    <div class="son1">
      <p class="p1">your team mate has been killed!</p>
      <p class="p2">I should stop playing COD</p>
    </div>
    <div class="son2"></div>
  </div>
</div>
</body>
</html>

How can this code be improved to avoid repeating the elements already printed in console?

Thanks!

David784
  • 6,356
  • 2
  • 20
  • 26
Julio Rodríguez
  • 429
  • 5
  • 18

0 Answers0