Open In App

D3.js selection.attr() Function

Last Updated : 19 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • name: It is the name of the attribute.
  • value: It is the value of the attribute.

Return Values: This function does not return any value.

Example 1:

HTML




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

HTML




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads