Testing the type of a DOM element in JavaScript

javascript

You can test the type of a DOM element in JavaScript using the instanceof operator or the nodeName property.

Here’s an example of using the instanceof operator to test if an element is a HTMLElement:

var element = document.getElementById("myElement");

if (element instanceof HTMLElement) {
  console.log("myElement is an HTMLElement");
} else {
  console.log("myElement is not an HTMLElement");
}

In this example, we retrieve an element with the ID myElement using document.getElementById(). We then use the instanceof operator to test if element is an instance of the HTMLElement class.

Alternatively, you can use the nodeName property to test the type of an element:

var element = document.getElementById("myElement");

if (element.nodeName === "DIV") {
  console.log("myElement is a div element");
} else {
  console.log("myElement is not a div element");
}

In this example, we retrieve an element with the ID myElement using document.getElementById(). We then test if the nodeName property of element is equal to “DIV”, indicating that it is a div element.

Note that the nodeName property returns the name of the tag in uppercase letters. To test for a specific element type, you must use the uppercase tag name.