Home > front end >  How to check if parent element has a child element
How to check if parent element has a child element

Time:12-16

I have a parent element which includes child element. But the child element appears only when the button click.

Initial parent element:

<div >
   <!--v-if-->
</div>

When the button is clicked:

<div >
   <div ></div>
</div>

So I want to see if the parent element has a child element or not. How can I do it with javascript?

CodePudding user response:

el.hasChildNodes- This can do the job but it will also count the non-element nodes.
el.children- This includes only element nodes.

let parent1 = document.getElementById("parent1");
let parent2 = document.getElementById("parent2");
let parent3 = document.getElementById("parent3")

console.log('Parent1 has child - ', parent1.hasChildNodes());
console.log('Parent1 has child - ', Boolean(parent1.children.length));

console.log('Parent2 has child - ', parent2.hasChildNodes());
console.log('Parent2 has child - ', Boolean(parent2.children.length));

console.log('Parent3 has child - ', parent3.hasChildNodes());
console.log('Parent3 has child - ', Boolean(parent3.children.length));
<!-- parent 1 -->
<div id="parent1"></div>

<!-- parent 2 -->
<div id="parent2">
  <div id="child1"></div>
</div>

<!-- parent 3 -->
<div id="parent3">
  <!-- comment -->
</div>

CodePudding user response:

That element does start out with child nodes (two text nodes and a comment node), just no element children.

If you want to know if it has any element children, you can use firstElementChild, which will be null if the element doesn't have any child elements, or the first child element if it does.

const x = document.querySelector(".parent");

console.log(`Before: ${!!x.firstElementChild}`);

// Emulate replacing the comment node with an element node
const div = document.createElement("div");
div.className = "child";
x.replaceChild(div, x.childNodes[1]);

console.log(`After:  ${!!x.firstElementChild}`);
<div >
   <!--v-if-->
</div>

CodePudding user response:

If you can have more than one child you can do it like this, using the property childNodes.

const parent = document.getElementById("app");

function getChild(parent) {
  if (!parent.hasChildNodes) return [];
  return [...parent.childNodes].filter(
    (element) => element.nodeName !== "#text"
  );
}

console.log(getChild(parent));
<div id="app">
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

You can check the child node with the "hasChildNodes()" method:

const parent = document.querySelector(".parent")

btnActions() => {
  this.addAChild()
  this.checkHasChild()
}

addAChild() => {
  parent.innerHTML = `<div ></div>`
}

checkHasChild() => {
  console.log(parent.hasChildNodes())
}

https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes

  • Related