Hackforge Academy

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');

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community