English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM hasAttribute() method

HTML DOM Element Object

hasAttribute()The method returns a boolean value indicating whether the specified element has the specified attribute.

UsagesetAttribute()Can add new attributes or change the value of existing attributes on the element.

Syntax:

element.hasAttribute(attrName)
var p = document.getElementsByTagName("P")[0];
p.hasAttribute("style");
Test and See‹/›

Browser compatibility

All browsers fully support the hasAttribute() method:

Method
hasAttribute()IsIsIsIsIs

Parameter value

ParametersDescription
attrNameA string representing the attribute name

Technical Details

Return Value:A boolean value that returns true if the element has the specified attribute, otherwise returns false
DOM Version:DOM 2Level

More Examples

Check if the anchor element has a target attribute. If so, change the value of the target attribute to "_blank":

//Get the <a> element with id = "myLink"
var a = document.getElementById("myLink");
//If the <a> element has a target attribute, set its value to "_blank"
if (a.hasAttribute("target")) {   
a.setAttribute("target", "_blank");
}
Test and See‹/›

Related References

HTML Tutorial:HTML Attributes

HTML DOM Reference:getAttribute() method

HTML DOM Reference:setAttribute() method

HTML DOM Reference:removeAttribute() method

HTML DOM Element Object