HTML DOM Element setAttribute() methode
- Previous Page scrollWidth
- Next Page setAttributeNode()
- Go Up One Level HTML DOM Elements Object
Definitie en gebruik
setAttribute()
De methode voegt de opgegeven eigenschap toe en geeft deze een opgegeven waarde.
Indien de opgegeven eigenschap al bestaat, wordt alleen de waarde ingesteld/veranderd.
Let op:Het HTMLElement-object van het HTML-document definieert ook JavaScript-eigenschappen voor alle standaard HTML-eigenschappen. Daarom moet deze methode alleen worden gebruikt wanneer niet-standaard eigenschappen moeten worden ingesteld.
Zie ook:
Referentiemanual:
Handleiding:
Voorbeeld
Voorbeeld 1
Voeg een class-eigenschap toe aan het 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.
Throws
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 its properties cannot be modified. |
Note
You can add a style attribute with a value to the element, but it is not recommended to do so as it will override other properties in the style attribute.
Please use the properties of the Style object:
Disadvantage:
element.setAttribute("style", "background-color:red;");
Advantage:
element.style.backgroundColor = "red";
Browser Support
element.setAttribute()
Is a DOM Level 1 (1998) feature.
All browsers fully support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous Page scrollWidth
- Next Page setAttributeNode()
- Go Up One Level HTML DOM Elements Object