How to Check If Element Has Any Children in JavaScript

How to check if element has any children in Javascript?

A couple of ways:

if (element.firstChild) {
// It has at least one
}

or the hasChildNodes() function:

if (element.hasChildNodes()) {
// It has at least one
}

or the length property of childNodes:

if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}

If you only want to know about child elements (as opposed to text nodes, attribute nodes, etc.) on all modern browsers (and IE8 — in fact, even IE6) you can do this: (thank you Florian!)

if (element.children.length > 0) { // Or just `if (element.children.length)`
// It has at least one element as a child
}

That relies on the children property, which wasn't defined in DOM1, DOM2, or DOM3, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at least as far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.

If you don't need IE8 and earlier support, you can also do this:

if (element.firstElementChild) {
// It has at least one element as a child
}

That relies on firstElementChild. Like children, it wasn't defined in DOM1-3 either, but unlike children it wasn't added to IE until IE9. The same applies to childElementCount:

if (element.childElementCount !== 0) {
// It has at least one element as a child
}

If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:

var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
hasChildElements = true;
break;
}
}

All of that is part of DOM1, and nearly universally supported.

It would be easy to wrap this up in a function, e.g.:

function hasChildElement(elm) {
var child, rv;

if (elm.children) {
// Supports `children`
rv = elm.children.length !== 0;
} else {
// The hard way...
rv = false;
for (child = element.firstChild; !rv && child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
rv = true;
}
}
}
return rv;
}

How to check if an element has a specific child?

Given references to two elements, you can test if one is the child of the other by using the .parentElement property as follows:

if (child1.parentElement === parent1) {
// do something
}

So in your specific case where you've said the parent is the body, you can do this:

    var child1 = document.createElement('div');    var child2 = document.createElement('div');    document.body.appendChild(child1); // note we only append one
if (child1.parentElement === document.body) { console.log("child1 is a child of the body"); // this will run } if (child2.parentElement === document.body) { console.log("child2 is a child of the body"); // this won't run }

Check if element has child node by id name

You can use querySelector():

var hasChild = parentDiv.querySelector("#child2") != null;

The querySelector() method lets you search the subtree beneath the starting element using the given CSS selector string. If the element is found, its DOM node is returned.

How to check if an element is only child of type?

You can check the length of children of the parentNode based on which you can you can remove the parent element of the targeted element.

Demo:

var btns = document.querySelectorAll('.myClass');Array.from(btns).forEach(function(b){  b.addEventListener('click', function(target){    if (this.parentNode.children.length == 1) {      this.parentNode.remove();    }    else alert('Has other child, can not be deleted');  })});
<div class="">Container 1  <button type="button" class="myClass">Delete</button>  <label>Some Other</label></div><div class="">Container 2  <button type="button" class="myClass">Delete</button></div><div class="">Container 3  <label>Some Other</label>  <button type="button" class="myClass">Delete</button></div>

How to check in Vue3 if an element has children?

You could use container.value.children in onMounted hook to check if the referenced element has children because in this hook the DOM is rendered.

const app = Vue.createApp({
setup() {
let container = Vue.ref(null)
Vue.onMounted(() => {

if (container.value && container.value.children.length) {

console.log("container has elements")
console.log(container.value.children)

} else {
console.log("container is empty")
}
})
return {
container
}
}
}).mount("#app")
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>

<div id="app">
<div ref="container">
<div>test</div>
</div>
</div>

Check whether a li element has any children with value using jQuery

This will solve your problem.

$("#navbarNavDropdown ul li").each(function() {  if ($(this).find("ul").length) {    alert('Yeah, we have a ul ' + $(this).text());  } else {    alert('No, we dont have a ul ' + $(this).text());    $(this).find('span').remove();  }})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="navbar-toggleable-sm collapse navbar-collapse justify-content-end" id="navbarNavDropdown">  <ul>    <li><a href="#">Level 1</a>      <ul>        <li><a href="#">Level 2<span class="caret" data-toggle="dropdown"><i class="fa fa-caret-down" aria-hidden="true"></i></span></a>          <ul class="dropdown-menu s-drop">            <li><a href="/vocational-school-programs/fl/jacksonville">Jacksonville</a></li>          </ul>        </li>      </ul>    </li>    <li class="dropdown mega-drop pstatic">      <a href="/admissions" class="mainmenuitem">Admissions<span class="caret" data-toggle="dropdown"><i class="fa fa-caret-down" aria-hidden="true"></i></span></a>    </li>  </ul></div>

JavaScript check if element is child

The following code may help you determine whether the two elements of parent-child relationships.

function isChild (obj,parentObj){
while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY'){
if (obj == parentObj){
return true;
}
obj = obj.parentNode;
}
return false;
}

then use the result of isChild call as condition if statement.

if(isChild(child,divElement)){
// doSomething...
}


Related Topics



Leave a reply



Submit