Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing the type of a DOM element in JavaScript

Is there a way to test the type of an element in JavaScript?

The answer may or may not require the prototype library, however the following setup does make use of the library.

function(event) {   var element = event.element();   // if the element is an anchor   ...   // if the element is a td   ... } 
like image 894
Casey Watson Avatar asked Oct 08 '08 21:10

Casey Watson


People also ask

What is the type of a DOM element?

Document object model. The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state. A DOM element is something like a DIV, HTML, BODY element on a page.

What is type element in JavaScript?

Definition and UsageThe type property sets or returns the value of the type attribute of an <object> element. The type attribute specifies the Internet media type (formerly known as MIME type) of the object.

How do you know if an element is visible in DOM?

is visible in DOM? visibility of the objects. Method 2: Using getComputedStyle() mETHOD: The getComputedStyle() method is used to return an object that contains all the CSS properties of the element. Each of these properties can now be checked for any property required.


2 Answers

You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.

In that case, use the elem.tagName or elem.nodeName property.

if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.

like image 101
FlySwat Avatar answered Sep 21 '22 02:09

FlySwat


if (element.nodeName == "A") {  ... } else if (element.nodeName == "TD") {  ... } 
like image 36
bobwienholt Avatar answered Sep 21 '22 02:09

bobwienholt