HTML DOM Element setAttribute() method
- Ƙarancin ƙarancin scrollWidth
- Ƙarancin ƙarancin setAttributeNode()
- Ƙaƙurmi ƙarancin HTML DOM Elements ɗanɗin
Definition and usage
setAttribute()
The method adds the specified attribute and assigns it the specified value.
If the specified attribute already exists, only set or change the value.
Note:The HTMLElement object in HTML documents also defines JavaScript properties corresponding to all standard HTML attributes. Therefore, you only need to use this method when you need to set non-standard attributes.
See also:
Reference manual:
Tutorial:
Instance
Example 1
Add class attribute to element:
element.setAttribute("class", "democlass");
Before adding:
Element object
After adding:
Element object
Example 2
Change the input field to a button:
myInput.setAttribute("type", "button");
Before changing:
After changing:
Example 3
Add the href attribute to the <a> element:
myAnchor.setAttribute("href", "");
Before adding:
Please visit codew3c.com
After adding:
Please visit codew3c.com
Example 4
Change the value of the target attribute to "_self":
if (element.hasAttribute("target")) { element.setAttribute("target", "_self"); }
Syntax
element.setAttribute(name, value)
Parameter
Parameter | Description |
---|---|
name | Required. The name of the attribute. |
value | Required. The new attribute value. |
Return value
None.
Throw
Exception | Description |
---|---|
INVALID_CHARACTER_ERR | Parameter name Characters that are not allowed to be used in HTML attribute names or XML attribute names. |
NO_MODIFICATION_ALLOWED_ERR | The current element is read-only and does not allow its properties to be modified. |
Note
You can add a style attribute with a value to the element, but it is not recommended to do so because it will override other properties in the style attribute.
Please use the Style object's properties:
Disadvantage:
element.setAttribute("style", "background-color:red;");
Advantage:
element.style.backgroundColor = "red";
Browser support
element.setAttribute()
Is DOM Level 1 (1998) feature.
All browsers fully support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Rarraba ƙoƙari | 9-11 | Rarraba ƙoƙari | Rarraba ƙoƙari | Rarraba ƙoƙari | Rarraba ƙoƙari |
- Ƙarancin ƙarancin scrollWidth
- Ƙarancin ƙarancin setAttributeNode()
- Ƙaƙurmi ƙarancin HTML DOM Elements ɗanɗin