How do I find a certain attribute exists or not for a selected item in jQuery?
For example, selected element jQuery('.button'), now this can have an attribute 'xyz'. How do I get whether it is having that or not?
How do I find a certain attribute exists or not for a selected item in jQuery?
For example, selected element jQuery('.button'), now this can have an attribute 'xyz'. How do I get whether it is having that or not?
You can use the hasAttribute method:
// Attach the event to the button
$('button').on('click', function() {
// This will refer the element from where event has originated
if (this.hasAttribute("style")) {
alert('yes')
} else {
alert('no')
}
})
If you want to use the jQuery library, you can directly use the attr
method in the if
condition.
if($('#yourElement').attr('someProp')){}
Alternatively, you can also use the jQuery is selector:
if ($(this).is('[style]')) {// rest of the code}
You have two solutions that I know of. 1) Native Javascript has a function for this .hasAttribute()
(e.g. $(this)[0].hasAttribute('name');
). 2) Using jQuery, you can check if $(this).attr('name')
is undefined or not.