JavaScript:D3 .attr()

vrun1208's avatar
Published Dec 31, 2023
Contribute to Docs

The .attr() method is used to set or get attributes of selected elements. This method is commonly used for styling elements by setting their attributes.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour

Syntax

selection.attr("attributeName", "attributeValue");

The .attr() function takes two parameters:

  • attributeName: Name of the attribute
  • attributeValue: Value of the attribute or a callback function.

Example

In the example given below, the value 5 is set to the attribute radius which turns the radius of circle to 5 units:

d3.select('circle').attr('radius', 5);

Output of the above example will be:

![example 1](https://raw.githubusercontent.com/vrun1208/docs/d3-styling-attr/media/d3-styling-attr-example.jpg)

The following example shows how to use the argument as a callback function. Based on the provided data, it is used to compute attribute values dynamically. Here, the circle’s parameter is calculated using the function:

d3.select('circle').attr('parameter', function (d) {
return 2 * 3.14 * d.radius;
});

All contributors

Contribute to Docs

Learn JavaScript:D3 on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour