HTML - DOMTokenList add() Method



HTML DOMTokenList add() method is used to add one or more tokens specified in parameter to the DOM TokenList.

Syntax

domtokenlist.add(token);

Parameter

This method accepts a single parameters as listed below.

Parameter Description
token It represents name of the token which you want to add to DOMTokenList.

Return Value

It does not return any value.

Examples of HTML DOMTokenList 'add()' Method

The following examples illustrates implementation of DOMTokenList add() method.

Adding a Class to Element

The following example illustrates add a class to any element using add() method. The added class changes the background and text color of the element.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOMTokenList add() Method
    </title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color");
        }
    </script>
</body>
</html>

Adding Multiple Classes to Element

In the following example, we have added multiple classes to a paragraph element.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOMTokenList add() Method
    </title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
        .font {
            font-size: 40px;
        }
        .align {
            text-align: center;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color", "font", "align");
        }
    </script>
</body>
</html>

Get Class Tokens of Element

In the following example, we get the names of classes added to HTML document.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOMTokenList add() Method</title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
        .font {
            font-size: 40px;
        }
        .align {
            text-align: center;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <p>Added class tokens are :</p>
    <p id="token"></p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color", "font", "align");
            document.getElementById("token").innerHTML = x;
        }
    </script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
add() Yes 8 Yes 12 Yes 3.6 Yes 5.1 Yes 12.1
html_dom.htm
Advertisements