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")) {
function etc()
}
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")) {
function etc()
}
You're so close it's crazy.
if($(this).attr("name"))
There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist.
This is why the below works. If you remove the name attribute from #heading the second alert will fire.
<script type="text/javascript">
$(document).ready(function()
{
if ($("#heading").attr("name"))
alert('Look, this is showing because it\'s not undefined');
else
alert('This would be called if it were undefined');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>
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>
The best way to do this would be with filter()
:
$("nav>ul>li>a").filter("[data-page-id]");
It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field.