.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:
![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;});
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.