Skip to content

JavaScript Tutorial The DOM

Changing HTML Attributes with JavaScript

Lesson 103 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

HTML attributes such as src, href, alt, disabled and type can all be read and changed.

Two ways

1. Methods that work with any attribute:

index.html
HTML
<a id="link" href="https://example.com">Example</a>
<script>
  const link = document.querySelector("#link");

  console.log(link.getAttribute("href"));          // → https://example.com
  link.setAttribute("href", "https://example.org");
  link.setAttribute("target", "_blank");
  link.removeAttribute("target");
  console.log(link.hasAttribute("target"));        // → false
</script>

2. Properties, which most standard attributes also have:

index.html
HTML
<img id="photo" src="" alt="">
<button id="save">Save</button>
<script>
  const photo = document.querySelector("#photo");
  photo.alt = "A mountain at sunrise";
  photo.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'><rect width='40' height='40' fill='orange'/></svg>";

  const save = document.querySelector("#save");
  save.disabled = true;
  console.log(save.disabled); // → true
</script>

Properties are shorter, and they use the right type (a real boolean for disabled, not the string "true").

Boolean attributes

Attributes like disabled, checked, hidden and required are boolean: their presence means true. Use the property.

script.js
JS
button.disabled = true;     // good
button.hidden = false;
checkbox.checked = true;

setAttribute("disabled", "false") still disables the button, because the attribute is present. Use the property, or toggleAttribute("disabled", false).

Attribute vs property: the value gotcha

For inputs, the value attribute is the starting value, and the value property is the current text.

index.html
HTML
<input id="field" value="start">
<script>
  const field = document.querySelector("#field");
  field.value = "changed by code";
  console.log(field.getAttribute("value")); // → start
  console.log(field.value);                 // → changed by code
</script>

Always read and write field.value for the current content.

Reading and changing many attributes

script.js
JS
const attributes = link.getAttributeNames();   // ["href", "id", ...]

Custom attributes: data-*

For your own information, use data- attributes, see Data Attributes.

Accessibility attributes

ARIA attributes are changed with setAttribute too, for example button.setAttribute("aria-expanded", "true"). See Accessible Buttons and ARIA.

lightbulb
Safe URLs
Setting href or src from user input can open security holes (for example javascript: URLs). See URL Validation.