Metodo setAttribute() dell'Elemento DOM HTML
- Previous Page scrollWidth
- Next Page setAttributeNode()
- Go Up One Level Oggetto Elements DOM HTML
Definizione e uso
setAttribute()
Il metodo aggiunge l'attributo specificato e assegna un valore specifico a esso.
Se l'attributo specificato esiste già, viene impostato o modificato solo il valore.
Attenzione:L'oggetto HTMLElement del documento HTML definisce anche le proprietà JavaScript corrispondenti a tutti gli attributi HTML standard. Pertanto, devi utilizzare questo metodo solo quando devi impostare attributi non standard.
Vedi anche:
Manuale di riferimento:
Tutorial:
Esempio
Esempio 1
Aggiungi l'attributo class all'elemento:
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.
Thrown
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 an element, but it is not recommended to do so as it will override other properties in the style attribute.
Please use the Style object's properties instead:
Disadvantage:
element.setAttribute("style", "background-color:red;");
Advantage:
element.style.backgroundColor = "red";
Browser Support
element.setAttribute()
It 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 Oggetto Elements DOM HTML