Recursive tree search node

Scenario: I have an unordered list of list items. Each list item contains a range, and an img tag is used in each range. So my html structure looks like this.

<ul class="slider-controls">
    <li data-preview1="./images/1.1.jpeg" data-preview2="./images/1.2.jpeg"><span><img src="./images/color1.jpeg"></img></span></li>
    <li data-preview1="./images/2.1.jpeg" data-preview2="./images/2.2.jpeg"><span><img src="./images/color2.jpeg"></img></span></li>
    <li data-preview1="./images/3.1.jpeg" data-preview2="./images/3.2.jpeg"><span><img src="./images/color3.jpeg"></img></span></li>
  </ul>

The img tags are just tiny square color swatches and the spans are in circles, so you basically have a set of colors of three color dots that the user can click on.

When the user clicks on li, I use javascript to capture the preliminary data to use this information to change the image. This works great if the user clicks slightly outside the circle. However, if they click inside the circle, they end up clicking on the img tag. But I need two parent nodes in the li tag!

So, I wrote a recursive function to solve this problem.

function findUpTag(el, tag) {
  console.log(el.tagName, tag);
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    } else {
      findUpTag(el.parentNode, tag);
    }
}

I use it like this: findUpTag(el, "LI");

I know that my recursive search works because I always get the output console.log ("success") when the current element === "LI".

However, my return value when I click on the image tag is always undefined! Even when my method finds LI!

What am I doing wrong?

+4
source share
1 answer

This is because you are not returning the result of a recursive call. You also need to handle the case el.parentNode null:

function findUpTag(el, tag) {
  console.log(el.tagName, tag);
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    } else {
      return el.parentNode ? findUpTag(el.parentNode, tag) : null; // <====
    }
}

FWIW, while you can use recursion for this, there is no need; there is only one way up the tree. So it could just be a loop:

function findUpTag(el, tag) {
  while (el) {
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    }
    el = el.parentNode;
  }
  return null;
}
+5
source

Source: https://habr.com/ru/post/1675938/


All Articles