Reputation: 3300
I am needing to determine the type of an element, possibly identified by the id
property of it.
For example, in the following form...
<form id='my-form'>
<input type='text' id='title' />
<textarea id='comment'></textarea>
</form>
I would like to have a way to identify that $('#title')
is a text box.
After some searches, I tried some thing like this, but it returns undefined
.
$('#title').type
But some thing like this seems to work, I don't know why...
$('#my-form :input').each( function() {
alert(this.type);
} );
The above will give text
and textarea
I guess. But when I use the first, it gives undefined.
given an ID of an element, how can I find the type of it.
Thank in advance.
Upvotes: 1
Views: 85
Reputation: 10003
input
is a normal tag, you should use:
$('#my-form input').each( function() {
alert(this.type);
});
This will return undefined:
$('#title').type
Because $("#title")
is a jQuery object and type
is a property of HTML Element. You can get HTML Element from jQuery object like this:
$('#title').get(0).type
Upvotes: 1
Reputation: 388316
You can use
if($('#title').is('input')){
alert('title in an input element')
} else if($('#title').is('textarea')){
alert('title in an textarea)
}
Upvotes: 1
Reputation: 121998
You can get the type of the element by writing
$("#target").attr('type');
or use
$("#target").get(0).tagName // return tag name like INPUT,TEXTAREA ..etc
Upvotes: 2