jQuery hasAttr checking to see if there is an attribute on an element
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) {
// ...
}
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>
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.
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.
Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty
<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 or is there but empty');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>