Metodo setAttribute() dell'Elemento 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:

Metodo getAttribute()

Metodo removeAttribute()

Metodo hasAttribute()

Metodo hasAttributes()

Metodo getAttributeNode()

Metodo setAttributeNode()

Metodo removeAttributeNode()

Tutorial:

Proprietà HTML

Esempio

Esempio 1

Aggiungi l'attributo class all'elemento:

element.setAttribute("class", "democlass");

Before adding:

Element Object

After adding:

Element Object

Try It Yourself

Example 2

Change the input field to a button:

myInput.setAttribute("type", "button");

Try It Yourself

Before changing:

After changing:

Example 3

Add the href attribute to the <a> element:

myAnchor.setAttribute("href", "");

Try It Yourself

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");
}

Try It Yourself

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