Changing Attributes in JavaScript

Javascript 7 min min read Updated: Mar 09, 2026 Intermediate
Changing Attributes in JavaScript
Intermediate Topic 4 of 15

In JavaScript, HTML elements often contain attributes such as id, class, src, href, and alt. These attributes define important properties of an element. Using the DOM, JavaScript can dynamically change these attributes to update the behavior or appearance of a webpage.

Changing attributes is commonly used when updating images, modifying links, enabling or disabling form elements, and dynamically updating webpage content.

Why Changing Attributes is Important

Modern web applications frequently update element attributes based on user actions. For example, a website may change an image source when a user clicks a button or update a link dynamically.

Key Point: JavaScript can modify HTML attributes dynamically without reloading the page.

Using setAttribute()

The setAttribute() method is used to change or add an attribute to an HTML element.

javascript let image = document.getElementById("myImage"); image.setAttribute("src", "new-image.jpg");
Output

The image source changes to "new-image.jpg"

Using getAttribute()

The getAttribute() method is used to retrieve the value of an attribute from an element.

javascript let link = document.getElementById("myLink"); console.log(link.getAttribute("href"));
Output

The current value of the href attribute is displayed

Using removeAttribute()

The removeAttribute() method removes a specified attribute from an element.

javascript let button = document.getElementById("submitBtn"); button.removeAttribute("disabled");
Output

The disabled attribute is removed and the button becomes clickable

Key Point: Removing attributes can enable or disable certain behaviors of elements.

Changing Attributes Directly

In many cases, attributes can also be modified directly using JavaScript properties.

javascript document.getElementById("myImage").src = "photo.jpg";
Output

The image source updates to "photo.jpg"

Common Attributes Modified with JavaScript

  • src – used for images
  • href – used for links
  • class – used for styling
  • disabled – used for form controls
  • alt – used for image descriptions

Conclusion

Changing attributes with JavaScript allows developers to modify the behavior and appearance of HTML elements dynamically. Methods like setAttribute(), getAttribute(), and removeAttribute() provide flexible ways to manage element attributes.

These techniques are widely used in modern web applications to update content, control form behavior, and create interactive user experiences.

In the next tutorial, you will learn about Changing Styles with JavaScript, where JavaScript is used to modify CSS properties of HTML elements dynamically.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators