Category: javascript
dom changing attributes setattribute getattribute
Published on 30 Sep 2026
Explanation
setAttribute() adds a new attribute or changes an existing attribute on an HTML element.
Code:
const link = document.getElementById('link');
link.setAttribute('href', '/home');
Explanation
getAttribute() reads the value of an HTML attribute.
Code:
const link = document.getElementById('link');
const url = link.getAttribute('href');
console.log(url);
Explanation
Attributes such as src and alt can be changed dynamically.
Code:
const image = document.getElementById('photo');
image.setAttribute('src', 'profile.jpg');
image.setAttribute('alt', 'Profile Photo');
Explanation
The disabled attribute can be added or removed dynamically from a button.
Code:
const button = document.getElementById('save');
button.setAttribute('disabled', 'true');
button.removeAttribute('disabled');
Explanation
data-* custom attributes can store additional information on HTML elements.
Code:
<button id="userBtn" data-user-id="101">
User
</button>
const id = document.getElementById('userBtn')
.getAttribute('data-user-id');