To check if an object is a DOM element in JavaScript, you can use the instanceof operator along with the HTMLElement or Node interface.
To do this we can write
function isDOMElement(obj) {
return obj instanceof HTMLElement || obj instanceof Node;
}
// Example usage:
var element = document.getElementById('myElement');
console.log(isDOMElement(element)); // Output: true
var notElement = "This is not an element";
console.log(isDOMElement(notElement)); // Output: false
In this example, the isDOMElement function takes an object as an argument and returns true if the object is an instance of HTMLElement or Node, indicating that it’s a DOM element. Otherwise, it returns false.
You can also use other methods like nodeType or nodeName to perform similar checks, but using instanceof with HTMLElement or Node is a commonly used approach.