How To Check If An Element Is A Div Using JavaScript?

How to Check if an Element is a Div using JavaScript

A Div element is most commonly used to divide the webpage and separate all the different webpage parts. Today we’ll show you how to check if an element is a Div using JavaScript. There are many ways to do it, but using the element.tagName property is the most efficient and straightforward way. Scroll down for more information about this property and other methods.

To check if an element is a Div using JavaScript

Here are two ways you can use to check whether an element is a Div tag or not:

Using element.tagName property

Syntax:

element.tagName

Description:

It returns the element’s tag name in uppercase.

If you want to check if an element is a Div, you can use the element.tagName property. This property will return the tag name of the element, which you can then compare to “DIV“.

First, we get the element we need to check with querySelector() and then call its tagName property. Note that the tagName property returns the name of the HTML tag in uppercase, so we have to compare it with ‘DIV‘ instead of ‘div‘.

<main id="app">
  <div class="header">
    <h1>Hello, This is LearnShareIT</h1>
  </div>
</main>
<script src="script.js"></script>
const header = document.querySelector(".header");

// Get the tagName of the header object and compare it with 'DIV'
if (header.tagName === "DIV") {
  console.log("This element is a Div");
} else {
  console.log("This element isn't a Div");
}

Output:

This element is a Div

To compare the tagName property of an element to ‘div‘ instead of ‘DIV‘, use the toLowerCase() method, for example:

const header = document.querySelector(".header");

// Use toLowerCase() if you want to compare with 'div'
if (header.tagName.toLowerCase() === "div") {
  console.log("This element is a Div");
} else {
  console.log("This element isn't a Div");
}

Output:

This element is a Div

Using the instanceOf operator

We already covered the syntax of the insatanceOf operator in this article. You can read more about it if you want.

The instanceOf operator is used to check whether an object is an instance of a particular class. We can use the instanceOf operator to check if an element is a Div using the following code:

element instanceof HTMLDivElement

See the example below for a better understanding.

const header = document.querySelector(".header");

// Check if the header object is an instance of HTMLDivElement
if (header instanceof HTMLDivElement) {
  console.log("This element is a Div");
} else {
  console.log("This element isn't a Div");
}

Output:

This element is a Div

Summary

We’ve shown you how to check if an element is a Div using JavaScript. The best practice is using the tagName property, but it’s good if you know more about the instanceOf operator.

Have a nice day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *