Manipulating Attributes

When retrieving an HTML Element using one of the method discussed above, each HTML Element is represented as an [Object] in JavaScript. Updating the properties of this object will also manipulate the HTML. From this object it is possible to add, remove or change an element's attributes, classes, text and even its inner HTML.

All native attribute (non-custom attributes), can be accessed as properties in the HTML Element Object. So if we were to have an anchor tag like the one below, we would be able to read, change, add, and remove its attributes.

<a id="link" href="https://facebook.com"></a>

Reading Attributes

The getAttribute()open in new window method returns the value of the specified attribute of the target element. If the attribute does not exist, value returned will be null or an empty string ("").

If we had the HTML example above, we can retrieve the values of the attributes using the getAttribute() method like so:

const link = document.getElementById('link')
console.log(link.getAttribute('id')) // link
console.log(link.getAttribute('href')) // https://facebook.com

It is important to note that most standard attributes can be accessed directly from an element, using the attribute name as the property.

const link = document.getElementById('link')
console.log(link.id) // link
console.log(link.href) // https://facebook.com

Changing Attributes

The setAttribute()open in new window method sets the value of an attribute on the specified element. If the attribute already exists, the value will be updated, else a new attribute will be added.

const link = document.getElementById('link')
link.setAttribute('href', 'https://twitter.com') // updates the attribute
link.setAttribute('target', '_blank') // adds a new attribute

It is also possible to use the attribute properties to update and add new properties.

const link = document.getElementById('link')
link.href = 'https://twitter.com' // updates the attribute
link.target = '_blank' // adds a new attribute

Note

This does NOT make changes to the HTML file itself. Only how the browser renders the HTML.

Removing Attributes

The removeAttribute()open in new window method removes an attribute from an element.

const link = document.getElementById('link')
link.removeAttribute('href')

NOTE

Using the removeAttribute() method is the preferred way to set an attribute to null, as attempting to do so with setAttribute() or the attribute property can have unexpected results.

This YouTube video was created by Steve Griffith.