Open In App

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:

Return Values: This function does not return anything.



Example 1: Setting the class name.




<!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>GeeksforGeeks</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:

GeeksforGeeks

Example 2: Unset the class name.




<!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">
            GeeksforGeeks
        </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:

GeeksforGeeks
null

Article Tags :