For examples in each method described in this article, we'll be using the following HTML elements:
<input type="email" id="email" name="email" />
<input type="password" id="password" name="password" />
<input type="submit" value="Submit" />
Using hasAttribute()
Function in JavaScript
JavaScript has a hasAttribute()
function which can be used to test whether an attribute exists on an element or not. It returns a boolean true
if a match is found and a boolean false
when no match is found. For example:
// usage 1: using pure JavaScript
document.getElementById('#email').hasAttribute('name');
// usage 2: using jQuery
jQuery('#email')[0].hasAttribute('name');
// usage 3: using jQuery
jQuery('#email').get(0).hasAttribute('name');
// output: true (boolean)
hasAttribute
is a JavaScript native function and is applied directly to an HTML element. When we select an element with jQuery, a jQuery object is returned with a collection of elements that match the specified selector. Therefore, to get the reference to the original HTML element we either use theget()
method or the array notation[]
when usinghasAttribute
with jQuery (where0
is the index which points to the first element in the collection of elements found by jQuery selector match).- For a jQuery selector that matches multiple HTML elements, we could iterate over each item and check for
hasAttribute
individually, for example by using thefor
loop or jQuery'sjQuery.each()
method.
Using With this
Keyword:
Let's assume this
keyword refers to an HTMLElement
, the following would be true:
this.hasAttribute('name');
jQuery(this)[0].hasAttribute('name');
jQuery(this).get(0).hasAttribute('name');
Evaluating the Return Value From jQuery's attr()
Method
const attr = $('#email').attr('name');
// attribute exists?
if (typeof attr !== 'undefined' && attr !== false) {
// do something...
}
- When an attribute does not exist on an element some browsers return it as
undefined
and some as booleanfalse
, therefore, we need to check for both values. - In ECMAScript 5 below,
undefined
can actually be overwritten, but this should not matter much if you're in control of the coding.
Direct Evaluation of attr()
Method's Return Value:
You may be wondering why we did not simply do:
if ($('#email').attr('name')) {
// do something...
}
In most cases, that may work for you, but in order to realize the problem with this method you need to know how it works. In JavaScript the following values are considered falsy (i.e. they evaluate to false
):
- Boolean
false
- Numeric
0
- An Empty String:
""
or''
null
undefined
NaN
All other values (non-falsy or truthy) evaluate to boolean true
. With that information we can conclude that since the return value of jQuery's attr()
is a string, a string boolean false, string 0, string null, and string NaN would be considered truthy values. However, the problem arises if the attribute is an empty string or undefined (i.e. has no value assigned) as these would all evaluate to boolean false
. For example, consider the following test cases:
Attribute | if (jQuery('#email').attr('name')) |
---|---|
name="email" |
true |
name="" |
false |
name |
false |
name="0" |
true |
name="false" |
true |
name="NaN" |
true |
name="null" |
true |
name="undefined" |
true |
Based on above information, remember to use this technique with caution!
Another popular technique is to use the double not notation (for example !!jQuery('#email').attr('name')
). It is same as directly evaluating the attr()
return value with the exception that it converts the value to a boolean true
or false
. The return values are the same as with the test cases above.
Select Elements With Specified Attribute Only
We could simply select elements via jQuery with an attribute selector (having the syntax, [attribute="value"]
). That way, only elements that actually have that attribute would be selected. We can then simply use JavaScript's length
property to check if there were any elements that matched like so:
// method 1
if (jQuery('#email[name]').length > 0) {
// do something...
}
// method 2: using is()
const elem = jQuery('#email');
if (elem.is('[name]')) {
// do something...
}
In context of this
, we could do the following:
if (jQuery(this).is('[name]')) {
// do something...
}
Similarly, we could use the filter()
method to filter out elements that do not have the specified attribute among a set of selected elements. For example:
const filtered = jQuery('input').filter('[name]');
if (filtered.length > 0) {
// do something...
}
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.