setAttribute and removeAttribute
Learn to add, change and remove attributes.
Adding attributes with setAttribute
To add or change an attribute on an HTML element, you use the setAttribute method. The first parameter is the attribute name and the second is its value.
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');If the attribute already exists, its value is changed; if not, it is added. This method always writes attribute values as strings.
getAttribute and removeAttribute
To read an attribute you use getAttribute; to delete it you use removeAttribute. Both take the attribute name as a single parameter.
const link = document.querySelector('a');
console.log(link.getAttribute('href'));
link.removeAttribute('target');Reading a missing attribute returns null; removing a missing one does not throw. Together with setAttribute, these three methods let you manage attributes comfortably.
Exercise Set href on the link
The link variable points to an <a> element. Use setAttribute to set href to 'https://example.com'. Then remove the target attribute.
Show example solution
link.setAttribute('href', 'https://example.com');
link.removeAttribute('target');
Test yourself
-
Which sets type='email' on the input?
const input = document.querySelector('input'); // A input.setAttribute('email', 'type'); // B input.attribute('type', 'email'); // C input.setAttribute('type', 'email'); // D input.setAttribute('type', email);- A
- B
- C
- D
Show answer
C — Correct! First the name, then the value: setAttribute('type', 'email').
-
Set the src attribute
const img = document.querySelector('img'); img.____('src', 'logo.png');Show answer
const img = document.querySelector('img'); img.setAttribute('src', 'logo.png'); -
Match methods
- setAttribute('id', 'x')
- Writes an attribute
- getAttribute('id')
- Reads the attribute
- removeAttribute('id')
- Removes the attribute