Definition and Usage
To get the value of a specified attribute from the element, use the getAttribute() function.
Syntax
element.hasAttribute(attributeName)
Parameters
attributeName |
Required. The name of the attribute to check for on the element (a string). |
|---|
Return Value
Returns true if the element has the specified attribute, and false if it does not.
Basic Example
<video src="video.mp4" autoplay></video>
const myVideo = document.querySelector("video");
console.log(myVideo.hasAttribute("src")); // true
console.log(myVideo.hasAttribute("autoplay")); // true
console.log(myVideo.hasAttribute("loop")); // false
Code Explanation
The querySelector() function returns the first element that matches the specified CSS selector within the HTML document or a specific element.
Practical Example
The hasAttribute() function is commonly used in conditional statements to check whether an element has a specific attribute.
The following example finds all links (<a> elements) on a website and changes them to open in a new tab.
<a href="https://example.com">example.com</a>
<a href="https://example.com">example.com</a>
<a href="https://example.com">example.com</a>
// Find all <a> elements in the document
const anchorEle = document.querySelectorAll("a");
// Iterate through each element using the forEach() function
anchorEle.forEach(ele => {
// If the element has an href attribute
if (ele.hasAttribute("href")) {
// Make the link open in a new tab
ele.setAttribute("target", "_blank");
// Apply the rel attribute for security when opening in a new tab
ele.setAttribute("rel", "noopener noreferrer");
}
});
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
For explanations of the functions and concepts used in this practical example, refer to the related topics below.
Browser Compatibility
| Method |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
hasAttribute()
|
1 | 12 | 1 | 1 |
Specifications
| Specification | |
|---|---|
hasAttribute()
|
DOM Standard #ref-for-dom-element-hasattribute① |
References
See Also
- JavaScript getAttribute() Function – Getting Attribute Values from Elements
- JavaScript removeAttribute() Function – Removing Specified Attributes from Elements
- JavaScript setAttribute() Function – Setting or Adding Attributes to Elements
- JavaScript toggleAttribute() Function – Toggling a Boolean Attribute on an Element
- JavaScript classList.contains() – Check Class Values of an Element