Open In App

D3.js selection.attr() Function

The selection.attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.

Syntax:



selection.attr(name[, value]);

Parameters: This function takes two parameters as shown above and described below:

Return Values: This function does not return any value.



Example 1:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width,initial-scale=1.0">
          
    <title>D3.js selection.attr() Function</title>
  
    <script src=
        "https://d3js.org/d3.v4.min.js">
    </script>
  
    <style>
        p {
            line-height: 5px;
        }
    </style>
</head>
  
<body>
    <div>
        <p>GeeksforGeeks</p>
    </div>
  
    <script>
        var div = d3.select("p")
            .attr("name", "This is from name attribute");
        var divselect = document.querySelector("p");
        console.log(divselect.getAttribute("name"));
    </script>
</body>
  
</html>

Output:

Example 2:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width,initial-scale=1.0">
  
    <title>D3.js selection.attr() Function</title>
  
    <script src=
        "https://d3js.org/d3.v4.min.js">
    </script>
  
    <style>
        p {
            line-height: 5px;
        }
    </style>
</head>
  
<body>
    <div>
        <a>GeeksforGeeks</a>
    </div>
      
    <script>
        var a = d3.select("a").attr("href", 
            "https://www.geeksforgeeks.org");
  
        var divselect = document.querySelector("a");
          
        console.log("This is from a attr href: ", 
                divselect.getAttribute("href"));
    </script>
</body>
  
</html>

Output:


Article Tags :