Testing the type of a DOM element in JavaScript

Casey Watson picture Casey Watson · Oct 8, 2008 · Viewed 124.8k times · Source

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
  ...
}

Answer

FlySwat picture FlySwat · Oct 8, 2008

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.