How to check if an element is nested inside another element using JavaScript?

0

Issue

I have an HTML structure like below. This structure is a nested list.

<ul id="u0">
    <li id="l1">
        <a id="a1"></a>
        <ul id="u1">
            <li id="l2">
                <a id="a2"></a>
            </li>
            <li id="l3">
                <a id="a3"></a>
                <ul id="u2">
                    <li id="l4">
                        <a id="a4"></a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

and looking for a JS function to identify whether an element is in a specific branch. For example if assume the function is function(id1,id2)

function('a4','l4') return true (a4 is a child of l4)
function ('a4','l2') returns false (a4 is not a child of l2)
function('a4','l1') returns true (a4 is a child of l1)

what I have done is to use children() and iterate the results but this did not work. I have a feeling that the answer is very short and I am overcomplicating a simple question.

Solution

You can use querySelector to query the parent, child and convert the result to a boolean:

const contains = (childId, parentId) => {
  return !!document.querySelector(`#${parentId}`).querySelector(`#${childId}`);
}

console.log(contains('a4', 'l4')) // return true (a4 is a child of l4)
console.log(contains('a4', 'l2')) // returns false (a4 is not a child of l2)
console.log(contains('a4', 'l1')) // returns true (a4 is a child of l1)
<ul id="u0">
  <li id="l1">
    <a id="a1"></a>
    <ul id="u1">
      <li id="l2">
        <a id="a2"></a>
      </li>
      <li id="l3">
        <a id="a3"></a>
        <ul id="u2">
          <li id="l4">
            <a id="a4"></a>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Answered By – Ramesh Reddy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More