Check if element exists inside another element with Javascript

2

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

For example: verifying that the div "child" is inside the "parent" to execute a function:

<div id="pai">
    <div id="filho"></div>
</div>
    
asked by anonymous 25.10.2017 / 18:17

3 answers

3

There, you simply try to select the element in the DOM and check its existence. For 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 fetched 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 entire 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>
    
25.10.2017 / 18:28
2

In% with_%, you can use CSS selectors, so you can use child combinator - querySelector .

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>
    
25.10.2017 / 18:53
0

You can use the div fetch through the parent div, for example:

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

    
25.10.2017 / 18:30