DEV Community

Cover image for How the DomTokenList API works
Lens
Lens

Posted on

How the DomTokenList API works

Table of Contents

What is it?

DomTokenList is a web API used to that’s a set of space seperate tokens (examples of tokens: Array or HTML Elements and Classes). It can be really helpful for specifec tasks needed in web development such as knowing the length of an array or adding CSS intereaction like different themes.

Properties

The DomTokenList only has two properties, length and value. You may know that the length property is used to see how long a string is or how many values. The value property on the other hand returns the value of a token without the string. For example with the property you can put a class name in HTML. Another difference is that you don't use the value property for arrays alot.

Value

/.
const head = document.querySelector("span");
const classes = head.classList;
const todo = classes.value;
console.log(todo);
//The output in the console would be the class name, but if you want to see it without the quotes you enter it in the HTML using the code below

head.textContent = todo;
Enter fullscreen mode Exit fullscreen mode

Length

//Lets say that a span element has the class a, b, and c
const span = document.querySelector("span");
const classes = span.classList;
const length = classes.length;
console.log(length);
//the output is 3 which is how many classes the span element has.

//you can also use it for arrays
 const arr = ["How", "Many", "Are", "There?"];
 const howLong = arr.length;
 console.log(howLong);
//The output is 4 which is how many elements there are

Enter fullscreen mode Exit fullscreen mode

Add and Remove

The add() and remove() do exactly as they say. You can add a token element or classList with the add method while being able to do the opposite with the remove method. You can use them by making buttons that changes the themes of a webpage like for the example i made below. We used the add method to add the something class when the button is clicked and used the remove method to remove the class when the user double clicks.

Toggle

Think of the toggle() method as the add and remove method together. It’ll either turn something on or off like a light switch. If we wanted to change our codepen that's above us to have only one function we would use that method. This is what it would look like:

function change() {
  document.body.classList.toggle('something');
}
Enter fullscreen mode Exit fullscreen mode

Now whenever we click the button the class will go on and off like a light switch, changing how webpage looks.

For Each

The forEach() method is used to call a function that iterates elements in an array or classList. In other words it adds a function for each element in an array or with the selected class. In the example below the output is each array element running seperately because the function runs for each of the elements and not all at once.

let students = ['Cady', 'Cam', 'Lens'];

// using forEach
students.forEach(myFunction);

function myFunction(item) {

 console.log('Hello ' + item);

}
Enter fullscreen mode Exit fullscreen mode

Replace

The replace() method is similar to the add method but instead of adding a class with the original you change the original class. Unlike the add method once you replace an array element or CSS class there’s no way to bring back the original. It uses two properties, the first being the old token that you’re going to replace and the second being your new token. The output in the console would be "I want to be a computer programmer".

const dream = "I want to be a basketball player";

// replace the first b with c
let result = dream.replace('basketball player', 'computer programmer');
console.log(result);

// The output would be "I want to be a computer programmer"

Enter fullscreen mode Exit fullscreen mode

Contain

The contain() method is used to search if a token has a specific key word or phrase or element. You can use let the user search for specific images or articles or add a function for those specific keywords. The output for the example below would be the console message since the elements class does have the key word 'water'

//Lets say that the river element has a class called "big water"
const island = document.querySelector('river');
const river = island.classList;

if (river.contains('water')) {
  console.log("There's water in the island!");
}
Enter fullscreen mode Exit fullscreen mode

Item

The item() method is used to return a list item from where it’s position is on the index. Therefor it uses the index property which is where the position of the wanted element is placed in. Since this can be used for both Class Lists and arrays you can use brackets and parentheses to place the index value in. It also uses the zero-index property to put the items in order. On the example below you can see that it picks the 2nd, in zero-index, classList to put as content for the heading.

//Lets say we had a heading with the class "Pick what's relavent"
const head = document.querySelector("h1");
const classes = head.classList;
const item = classes.item(2);
head.textContent = item;
//The HTML output would be a heading saying "relavent"
Enter fullscreen mode Exit fullscreen mode

Keys and Values

While the key() method returns an Iterator that has all the keys from the selected token list, the values() property returns the iterator that has all the values from the token list. The key method creates a zero-index order of the selected token list. The values method on the other hand puts the values of a token list in zero-index order. Neither does the others job.

On the example below lets say we have an h1 element that has the class "How many do i have". Since each spaced word is a value in the class list when we use the values method it'll put in all of those values seperately. The keys method instead returns a numbered zero-index list of where each value is.

Keys

const head = document.querySelector("h1");
const classes = head.classList;
const item = classes.keys();

for (let value of item) {
  head.textContent += `(${value}) `;
}
//The output in HTML is the keys in a zero-index order
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Values

const head = document.querySelector("h1");
const classes = head.classList;
const item = classes.values();

for (let value of item) {
  head.textContent += `${value}`;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Entries

The entries() method will return an iterator with a key and a value. In other words it's pretty much the keys and values method put together. The order is zero-indexed (meaning it starts at 0) with the key showing the numbered order. For example from our previous codes above we can replace it with the entries method to have both the class list's values and the keys.

const head = document.querySelector("h1");
const classes = head.classList;

const iterator = classes.entries();

for (const value of iterator) {
  console.log(`(${value})`);
}
//The output is each every entry for the class list
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Support

The supports method is used to add a specific function when a given token is in the associated attribute's supported tokens. For examples if an element allows download you can make it say a message in the console then put a function if something else happends. It may be one of the least used methods but for statistics like a compatibility checker it can sometimes be useful! In the example below it's checking if a heading supports downloads and if it does or does not a certain message in the console will be shown

const head = document.querySelector('h1');

if (head.sandbox.supports('allow-downloads')) {
console.log("Yes!!");
}
else {
console.log("noo!!");
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

With the DomTokenList API, we can run any code that intereacts with the token list quickly. We can also use it to help style our webpages and bring more interaction. All of this information is from what i've learned last week that i've saved in notion. Thank you for reading :)

Oldest comments (0)