Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JQuery hasAttr checking to see if there is an attribute on an element

How do you check if there is an attribute on an element in jQuery? Similar to hasClass, but with attr?

For example,

if ($(this).hasAttr("name")) {
// ...
}
by

3 Answers

akshay1995

var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
// ...
}
kshitijrana14
How about just $(this).is("[name]")?

The [attr] syntax is the CSS selector for an element with an attribute attr, and .is() checks if the element it is called on matches the given CSS selector.
pankajshivnani123
If you will be checking the existence of attributes frequently, I would suggest creating a hasAttr function, to use as you hypothesized in your question:

$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};

$(document).ready(function() {
if($('.edit').hasAttr('id')) {
alert('true');
} else {
alert('false');
}
});

<div class="edit" id="div_1">Test field</div>

Login / Signup to Answer the Question.