JavaScript .setAttribute()

Anonymous contributor's avatar
Anonymous contributor
Published Mar 18, 2025
Contribute to Docs

The .setAttribute() method of the Element interface sets or updates an attribute of the specified element. If the given attribute already exists, its value is updated; otherwise, a new attribute is created with the given name and value.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

elm.setAttribute(name, value);
  • elm: The element on which the .setAttribute() method is called.
  • name (string): The name of the attribute to set (e.g., "class", "id", "href").
  • value (string): The value to assign to the specified attribute.

Example

This example sets the "name" attribute of a button element to "helloButton":

const button = document.querySelector('button');
button.setAttribute('name', 'helloButton');

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours