Check If the Content of the Element is Empty with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to check if the content of the element is empty with JavaScript.

Introduction

The following is the HTML used in this article.

<div id="box">
  <h1>Lorem Ipsum</h1>
  <div id="el"></div>
</div>
Sponsored links

Check if the element is empty with childNodes

The childNodes is a property that returns the child nodes of the specified element in NodeList.
Get the number of child nodes and check if the contents are empty.

JavaScript

let el = document.getElementById('el');

if(el.childNodes.length === 0){
  console.log("The element is empty");
}

Since it is judged by the length of Node, it will not be empty judgment if it has a text node.

Sponsored links

Check if the element is empty with children

The children is a property that returns the elements of the specified node.
Get the number of elements that a node has and check if the contents are empty.

JavaScript

let el = document.getElementById('el');
if(el.children.length === 0){
  console.log("The element is empty");
}

Since it is judged by the length of Node, it will not be empty judgment if it has a text node.