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:

  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Example 2:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.