I have a function:
function Check(o) { alert(/* o is a DOM element ? "true" : "false" */); }
How can I check if the parameter o
is a DOM object or not?
To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.
Definition and Usage. The nodeType property returns the node type, as a number, of the specified node. If the node is an element node, the nodeType property will return 1. If the node is an attribute node, the nodeType property will return 2. If the node is a text node, the nodeType property will return 3.
Use the tagName property to check if an element is a div, e.g. if (div. tagName === 'DIV') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.
A DOM element implements the Element
interface. So you can use:
function Check(o) { alert(o instanceof Element); }
Check if the nodeName
property exists.
Basically check if it is a Node
: look at the DOM lvl 1 specs, check the Node definition.
If you meant it literally when you said Element
check for tagName
property, look at the Element definition in the same spec
So to recap, do either
function Check(o) { alert(o.tagName ? "true" : "false"); }
to check if it is a DOM Element or
function Check(o) { alert(o.nodeName ? "true" : "false" ); }
to check if it is a DOM Node
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With