How to check a JavaScript Object is a DOM Object ?
Checking if a JavaScript object is a DOM object involves verifying whether the object represents an element or component within the Document Object Model (DOM) of an HTML or XML document. This can be done by checking if the object is an instance of Node, Element, or other specific DOM interfaces.
What is DOM (Document Object Model)?
The DOM (Document Object Model) is a programming interface that represents the structure of HTML or XML documents as a tree of objects, allowing dynamic manipulation of content.
Element
In HTML DOM, Element is the general base class for all objects. An Element object represents all HTML elements.
Approach: Using instanceof operator.
To check if a JavaScript object is a DOM object, use the instanceof operator. This operator determines whether the object is an instance of the Element class. If true, it indicates the object is part of the DOM, enabling dynamic HTML manipulation.
Syntax
Object instanceof ObjectType
Parameters:
- Object: It stores the Object which need to be tested.
- ObjectType: It stores the Object Type to be tested against.
Example: In this example we checks if a JavaScript object is a DOM element using instanceof Element. It updates the content of div elements based on whether the object is a DOM element or not.
<!DOCTYPE HTML>
<html>
<head>
<title>
How to check a JavaScript Object is a DOM Object?
</title>
</head>
<body>
<div id="div1"></div>
<div id="nonElem"></div>
<script>
// Check if object is a DOM Element
function isDOM(Obj) {
return Obj instanceof Element;
}
// Get elements
let div = document.getElementById('div1');
let nonElem = document.getElementById('nonElem');
// Non-DOM object
let x = 1;
// Check and update innerHTML
if (isDOM(div))
div.innerHTML = "Div is detected as a DOM Object";
if (!isDOM(x))
nonElem.innerHTML = "x is detected as a non-DOM Object";
</script>
</body>
</html>
Output:
Div is detected as a DOM Object
x is detected as a non-DOM Object