Check existence of an attribute with JavaScript/jQuery
This post will discuss how to check whether an element has the specified attribute or not in JavaScript and jQuery.
1. Using jQuery
The idea is to use the .attr() method, which returns the attribute’s value for an element if it is present and returns undefined if the attribute doesn’t exist.
JS
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($("#container").attr('name') !== undefined) { alert('The name attribute exists'); } else { alert('The name attribute does not exist'); } }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" name="login"></div> </body> </html> |
Alternatively, you can use the Has Attribute Selector [name] to select elements having the specified attribute.
JS
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($("#container[name]").length) { alert('The name attribute exists'); } else { alert('The name attribute does not exist'); } }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" name="login"></div> </body> </html> |
2. Using JavaScript
In pure JavaScript, you can use the hasAttribute() method to determine whether the specified element has the specified attribute.
JS
|
1 2 3 4 5 6 7 8 |
var obj = document.getElementById('container'); if (obj.hasAttribute('name')) { alert('The name attribute exists'); } else { alert('The name attribute does not exist'); } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" name="login"></div> </body> </html> |
That’s all about checking the existence of an attribute in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)