Check if element exists inside another element with Javascript

Asked

Viewed 7,670 times

2

Is there any way I can check if one structure exists inside another with Javascript?

For example: check whether the div "child" is within the "father" to perform a function:

<div id="pai">
    <div id="filho"></div>
</div>

3 answers

3


There is, just try to select the element in the DOM and verify its existence. When it comes to elements with the attribute id defined, just do:

const pai = document.getElementById("pai");
const filho = pai.querySelector("#filho");

if (filho !== null) {
  console.log("O elemento #filho existe em #pai");
} else {
  console.log("O elemento #filho não existe em #pai");
}
<div id="pai">
    <div id="filho"></div>
</div>

Notice the child element was searched with reference to the object pai. This means that the search will be done only in the DOM tree defined by the parent element, not the whole document.

See working in a situation where the child element does not exist:

const pai = document.getElementById("pai");
const filho = pai.querySelector("#filho");

if (filho !== null) {
  console.log("O elemento #filho existe em #pai");
} else {
  console.log("O elemento #filho não existe em #pai");
}
<div id="pai">
    
</div>

  • Great, that’s right, well explained.

2

In querySelector it is possible to use CSS selectors, so it is possible to use Child - pai > filho.

const elem = document.querySelector("#pai > #filho");

if (elem) {
  console.log("Elemento encontrado");
} else {
  console.log("Elemento nao encontrado");
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
s
<div id="pai">
    <div id="filho"></div>
</div>

  • 1

    Opá, even better!

  • 1

    Well remembered. + 1

0

You can use the search in the gift through the father div, for example:

js pai = document.querySelector('.pai'): possui_div_filho = pai.querySelector('.filho') != null;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.