murvinlai
murvinlai

Reputation: 50385

What type of DOM Element?

e.g. if i have this:
<div id='mydiv'>whatever</div>

then let say in jQuery, how can I find out that the dom element with id "mydiv" is a DIV or is some other element type.

e.g. 
$('#mydiv').????  ?

Upvotes: 40

Views: 41976

Answers (6)

James Jackson
James Jackson

Reputation: 788

The .prop() function is a nice way of doing this.

// Very jQuery
$('#mydiv').prop('tagName');

// Less jQuery
$('#mydiv')[0].tagName;

Both give the same result.

And, as Aram Kocharyan commented, you'll probably want to standardise it with .toLowerCase().

Upvotes: 4

Shaz
Shaz

Reputation: 15887

alert($('#mydiv')[0].nodeName);

Upvotes: 5

John Strickler
John Strickler

Reputation: 25421

var type = $('#mydiv')[0].tagName

alert(type);
//displays "DIV"

Upvotes: 56

Ross
Ross

Reputation: 17987

var domElement = $('#mydiv').get(0);
alert(domElement .tagName);

may be of use.

Upvotes: 1

Doug Stephen
Doug Stephen

Reputation: 7351

$('#mydiv').get(0).nodeType if you know there's only one element. The selector object can contain an array of objects.

.get() returns the array of DOM objects, the parameter indexes. nodeType is a property exposed by the DOM that tells you what the type of the DOM node is. Usually as a String in all caps IIRC.

CORRECTION nodeType gives you an INT corresponding to a nodeType. tagName is what you want.

Upvotes: 1

Michael Haren
Michael Haren

Reputation: 108376

Try is which tests if anything in the given set matches another selector:

if( $('#mydiv').is('div') ){
  // it's a div
}

You can also get the tag this way:

$('#mydiv').get(0).tagName // yields: 'DIV'

Upvotes: 50

Related Questions