Add a class attribute to an element:
element.setAttribute("class", "democlass");
Before:
After:
More examples below.
The setAttribute()
method sets a new value to an attribute.
If the attribute does not exist, it is created first.
element.setAttribute(
name,
value)
Parameter | Description |
name | Required. The name of the attribute. |
value | Required. The new attribute value. |
NONE |
It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute.
Use Properties of the Style Object instead:
element.setAttribute("style", "background-color:red;");
element.style.backgroundColor = "red";
Change an input field to an input button:
myInput.setAttribute("type", "button");
Before:
After:
Add a href attribute to an <a> element:
myAnchor.setAttribute("href", "https://www.91xjr.com");
Before:
After:
Try it Yourself »Change the value of the target attribute to "_self":
if (element.hasAttribute("target")) {
element.setAttribute("target", "_self");
}
Try it Yourself »
element.setAttribute()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!