Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is a DOM element? [duplicate]

Tags:

javascript

dom

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?

like image 977
BrunoLM Avatar asked Jan 21 '11 00:01

BrunoLM


People also ask

How do you know if something is in DOM?

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.

What is nodeType in JavaScript?

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.

How do I check if an element is in HTML?

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.


2 Answers

A DOM element implements the Element interface. So you can use:

function Check(o) {     alert(o instanceof Element); } 
like image 179
David Hellsing Avatar answered Sep 28 '22 04:09

David Hellsing


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

like image 25
Martin Jespersen Avatar answered Sep 28 '22 05:09

Martin Jespersen