JavaScript:D3 .attr()
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.
Syntax
selection.attr("attributeName", "attributeValue");
The .attr() function takes two parameters:
attributeName: Name of the attributeattributeValue: 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:

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;});
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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