Reputation: 1697
I have the following code to loop through all rect nodes:
d3.selectAll("svg g rect")
.on('mouseover', function (d) {
console.log(this);
});
Console.log prints:
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="805.625" y="0" width="13.75" height="229.018" >...</rect>
How can I access name attribute (having value "UK"
) of rect tag? I tried this.name
but it doesn't work.
Upvotes: 0
Views: 47
Reputation: 102218
The idiomatic D3 way to get the value of name
is using selection.attr()
as a getter:
d3.select(this).attr("name")
Here is the demo:
d3.select("rect")
.on('mouseover', function(d) {
console.log(d3.select(this).attr("name"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>
Internally, selection.attr()
uses getAttribute
(or getAttributeNS
). Therefore, it's equivalent to:
this.getAttribute("name")
And here is the demo:
d3.select("rect")
.on('mouseover', function(d) {
console.log(this.getAttribute("name"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>
Upvotes: 3