views:

5993

answers:

4

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 element is and anchor
  ...
  // if element is a td
  ...
}
+6  A: 
if (element.nodeName == "A")
{
}
else if (element.nodeName == "TD")
{
}
bobwienholt
+1 cause using **UPPERCASE** is not an option! ;)
aSeptik
+3  A: 

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 elem.tagName or elem.nodeName.

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

FlySwat
+4  A: 

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

roenving
Beware of the case of tagName.
eyelidlessness
yes, it looks like tagName will return uppercase tag names.
Casey Watson
+2  A: 

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

Eric Wendelin