العودة إلى الدورة

Modifying Attributes: getAttribute, setAttribute, removeAttribute

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

82. Modifying Element Attributes

Attributes (like href, class, src, id) define the characteristics of an HTML element. JavaScript provides methods to manage them.

1. Getting Attributes: getAttribute()

Retrieves the value of a specific attribute.

html A placeholder

javascript const image = document.getElementById('photo');

let currentSrc = image.getAttribute('src'); // default.jpg console.log(currentSrc);

2. Setting Attributes: setAttribute()

Sets or changes the value of an attribute.

javascript image.setAttribute('src', 'user-profile.png'); image.setAttribute('alt', 'User profile picture');

// Set a custom data attribute image.setAttribute('data-id', 456);

3. Removing Attributes: removeAttribute()

Removes the specified attribute entirely.

javascript image.removeAttribute('alt');