Reputation: 50385
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
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
Reputation: 25421
var type = $('#mydiv')[0].tagName
alert(type);
//displays "DIV"
Upvotes: 56
Reputation: 17987
var domElement = $('#mydiv').get(0);
alert(domElement .tagName);
may be of use.
Upvotes: 1
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
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