Suppose you want to set an attribute without a value to one or more DOM elements in your HTML markup.
What is the best way to accomplish this?
Earlier in the day, I had to answer this question for myself when I implemented Joshua Johnson’s Animate JavaScript library to trigger CSS animations for elements when they become visible in the viewport.
Now that I am done with it, I’d like to share what worked out for me with you.
To set an attribute without a value in JavaScript, use the Element.setAttribute(name, value)
method. The method creates an attribute with the specified values or updates the attribute if it already exists.
The Element.setAttribute(name, value)
method is part of the Element
API, and has full browser support. In turn, the Element
API is an interface within the broader Web APIs specification, which all modern browsers have support for.
Any experienced JavaScript developer will tell you that Web APIs are there to simplify your functions by providing you with built-in, natively-supported interfaces and methods for accessing elements from DOM and performing operations on them.
How This Works
The syntax for this method is as follows:
Element.setAttribute(name, class);
Where Element
stands for the DOM element/s that you want to target, name
for the name of the custom HTML attribute to add/update, and class
for the value of the class that goes between that custom HTML attribute’s quotation marks.
To set an attribute without a value, do this:
// Create an an attribute named "my-attribute" without a value
Element.setAttribute('my-attribute', '');
On success, your function will add an attribute without a value to the DOM element that you targeted. Or, if the DOM element already had an attribute with this name, it would update and empty it.
Examples
Set Empty Attribute to the First Element
Suppose you had a <div> element with an ID of #my-element, and you wanted to set an empty attribute named “custom-attribute” for it.
Though there’s more than one way to do this, the simplest would be to add a JavaScript code snippet before the end of the <body> tag to target the DOM element and create the empty attribute within it.
To target the first DOM element, we use the Element.querySelector()
method in JavaScript:
<html>
<head>
</head>
<body>
<!-- The DOM element -->
<div id="my-element">Hello world!</div>
<!-- JavaScript code snippet -->
<script>
document.querySelector('#my-element').setAttribute('custom-attribute', '');
</script>
</body>
</html>
The script targets the first occurence of #my-element
, then adds an empty custom-attribute
to its list of attributes:
Set Empty Attribute to the Second, Third, or n-th Element
To target an n-th, and not the first, element, use the :nth-child() selector in CSS.
Let’s take our example code from above. We’ll add three <div> elements this time and, instead of an ID of #my-element
, we will assign them a CSS class of .my-element
.
To target the second element, we use the querySelector() method with an argument of .my-element:nth-child(2)
as you will see in the code snippet below:
<html>
<head>
</head>
<body>
<!-- The DOM elements -->
<div class="my-element">Hello world!</div>
<div class="my-element">Hello world!</div>
<div class="my-element">Hello world!</div>
<!-- JavaScript code snippet -->
<script>
document.querySelector('.my-element:nth-child(2)').setAttribute('custom-attribute', '');
</script>
</body>
</html>
The JavaScript code snippet, as expected, sets an attribute without a value to the second DOM element in our HTML markup with a CSS class of .my-element
:
Set Empty Attribute to Multiple Elements
What if you want to set an attribute without a value to multiple DOM elements with JavaScript?
We will do this by using the querySelectorAll()
method instead of querySelector()
, which returns a NodeList of all elements matching our CSS selector.
(The main reason behind this is that the querySelector()
no longer works for us; it returns only the first element that matches the target—not all elements that do.)
Then, we will iterate through each of the elements in the NodeList with the Element.setAttribute()
method, which you are already familiar with:
<html>
<head>
</head>
<body>
<!-- The DOM elements -->
<div class="my-element" custom-attribute="">Hello world!</div>
<div class="my-element" custom-attribute="">Hello world!</div>
<div class="my-element" custom-attribute="">Hello world!</div>
<!-- JavaScript code snippet -->
<script>
var elementsList = document.querySelectorAll('.my-element');
for (var i=0; i < elementsList.length; i++) {
elementsList[i].setAttribute('custom-attribute', '');
}
</script>
</body>
</html>
The result:
Avoid These Mistakes
Omitting the Second Argument
It’s important to note that, when typing your argument, both name
and class
are required. So if you try to do it like this:
// Omitting the class from the argument won't work
Element.setAttribute('my-attribute');
The browser will throw an “Uncaught TypeError: Failed to execute ‘setAttribute’ on ‘Element’: 2 arguments required, but only 1 present.” in the console.
So save yourself the headache by making sure that you’ve typed in both the name
and class
arguments in your statement, with the former set to whatever you like and the latter with empty quotation marks.
Wrong Selector
If you want to target more than one DOM element and you use the querySelector()
method, your function won’t work.
Instead, make sure to use the querySelectorAll()
method to get a NodeList of all the elements that you can then iterate on.
Mistyped Target
It happens to the most meticulous among us that, every now and then, we get the target DOM element wrong.
In such a case, even though our function is coded correctly, the selector returns a null for querySelector()
and an empty NodeList for querySelectorAll()
.
The good news, as you can see from the snapshot above, is that you can easily get to the root cause for this from your browser’s console.