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 > </ 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 > </ 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