A collection of typeset blocks and typesetting tools

In addition to creating new tags and content, JavaScript is frequently used to modify the attributes of elements that already exist on the page: for example, to change the src attributes inside a <video> element to create a simple video playlist. This is also true of elements that are in the process of being created, i.e. adding attributes to elements so they are complete before they are added to the page.

Once you have identified the element(s) to work on, the methods to add, remove and modify attributes are fairly straightforward:

Adding an attribute to an element with setAttribute

If we have any element, let’s say the first <video> element on the page, identified with querySelector:

var video = document.querySelector("video");

…then we can add a poster attribute and its associated value to the element with setAttribute:

video.setAttribute("poster", "woke.jpg");

The result in the DOM:

<video poster="woke.jpg" autoplay src="">

If the attribute is already present, setAttribute will modify its value to whatever is inside the method.

Removing an attribute

Removing an attribute from an element uses, not surprisingly, the removeAttribute method. The method only requires the name of the attribute:


If the attribute isn’t set on the element when you attempt to remove it, JavaScript won’t throw an exception: your script will continue to run without any errors. However, you can check that an element has an attribute by using hasAttribute, which we will look at next:

Checking if an element has an attribute

Before modifying an attribute, it makes sense to check that the element under inspection has that attribute present. We can do that with hasAttribute, which is usually framed as the decision of an if statement:

if (video.hasAttribute("autoplay")) {
    // take action

You can get a list of all the attributes applied to an element with the .attributes property, which I will discuss at length in a future article.

Photograph by Marcin Wichary, used under a Creative Commons Generic 2.0 license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.