Thursday, September 4, 2025
HomeLanguagesJavascriptD3.js selection.classed() Function

D3.js selection.classed() Function

The selection.classed() function is used to set the class to the selected element. This function can also be used to unset the class to a particular element that is selected.

Syntax:

selection.classed(names[, value]);

Parameters: The above-given function takes two parameters which are given above and described below:

  • name: It is the name of the class to be given to the element that is selected.
  • value: It is the boolean value i.e true or false to set or unset the class.

Return Values: This function does not return anything.

Example 1: Setting the class name.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent="width=device-width, 
                    initial-scale=1.0">
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <div>
        <a>neveropen</a>
    </div>
  
    <script>
  
        // Sets the class to the a tag
        var a = d3.select("a")
            .classed("className", true);
          
        // This will select the anchor tag
        var divselect = document.querySelector(".className");
        console.log(divselect.innerHTML);
    </script>
</body>
  
</html>


Output:

neveropen

Example 2: Unset the class name.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent="width=device-width, 
                    initial-scale=1.0">
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <div>
        <p class="classGiven classGiven2">
            neveropen
        </p>
    </div>
  
    <script>
  
        // Unsets the class named classGiven
        // to the "p" tag
        var a = d3.select("p")
            .classed("classGiven2", false);
  
        // This will select the "p" tag
        var divselect = document
            .querySelector(".classGiven");
              
        console.log(divselect.innerHTML);
  
        // This will not select the "p" tag
        // As the classGiven 2 is unset
          
        var divselect = document
            .querySelector(".classGiven2");
  
        console.log(divselect);
    </script>
</body>
  
</html>


Output:

neveropen
null
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6628 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS