Home > Software engineering >  how can i detect if a parent element has a specific child element with javascript?
how can i detect if a parent element has a specific child element with javascript?

Time:08-15

I have a div that has a "span" and I am dynamically adding "div" tags with a class to identify them, so my question is: how can I know if my parent "div" tag has new div tag children without counting the tag "span"? because my problem is that the e[i].children.length function is always considering the span title as a child

In summary I need to know how many child div tags the parent div has (excluding all other html tags that can be added)

let e = document.getElementsByClassName('classDiv')

for (let i = 0; i < e.length; i  ) {

  if (e[i].children.length > 0) {
    console.log("has children");
  } else {
    console.log("has no children");
  }
}
<div id="parent" >
  <span id="title">title</span>
  <div>children1</div>
  <div>children2</div>
  <div>children3</div>
</div>

CodePudding user response:

Try

var e = document.querySelectorAll('#parent > div');
console.log(e.length ? "has children" : "has no children");

The > selector is used to select elements with a specific parent

CodePudding user response:

document.getElementById("parent").getElementsByTagName("div")

Will return all the child element that are divs.

You can also do the same with getElementsByClassName instead of getElementById, while iterating over the results, and using the same getElementsByTageName on each one.

  • Related