Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Managing Attributes

HTML elements have attributes (like id, class, src).

Using the DOM, JavaScript can get, set, check, or remove these attributes dynamically.

๐Ÿ”น 1. getAttribute()

๐Ÿ‘‰ Reads the value of an attribute.

Syntax

element.getAttribute(attributeName);

Example

<input id="username" type="text">
const input = document.getElementById("username");
console.log(input.getAttribute("type"));
text

๐Ÿ”น 2. setAttribute()

๐Ÿ‘‰ Adds or updates an attribute.

Syntax

element.setAttribute(name, value);

Example

input.setAttribute("placeholder", "Enter username");

Result in HTML

<input id="username" type="text" placeholder="Enter username">

๐Ÿ”น 3. removeAttribute()

๐Ÿ‘‰ Removes an attribute from an element.

Syntax

element.removeAttribute(name);

Example

input.removeAttribute("placeholder");

Result

The placeholder attribute is removed.

๐Ÿ”น 4. hasAttribute()

๐Ÿ‘‰ Checks if an attribute exists.

Syntax

element.hasAttribute(name);

Example

console.log(input.hasAttribute("id"));
console.log(input.hasAttribute("class"));
true
false

๐Ÿ”น Attribute vs Property (Quick Tip)

  • Attribute โ†’ Defined in HTML

  • Property โ†’ Exists on DOM object

Example

input.value = "Bhaskar";
console.log(input.getAttribute("value"));
null

โœ”๏ธ value is a property, not an HTML attribute.


โœ… Summary Table

Method

Purpose

getAttribute()

Read attribute value

setAttribute()

Add or update attribute

removeAttribute()

Remove attribute

hasAttribute()

Check attribute exists


๐Ÿ“Œ Key Note:

Use properties for dynamic values (value, checked),

use attributes for static HTML-related data (id, class, src).