Testing the type of a DOM element in JavaScript
javascriptYou 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.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame