How to assign a unique identifier to an SVG text element in d3 javascript

Creating a histogram in d3. I have 30+ bars, with 30+ corresponding inscriptions on the x axis. I would like the X axis labels to be hidden when the page loads (this works), AND APPEAR only if the user cursor is over the corresponding panel (SVG object). To do this, I assign an identifier to each rectangle and each text element. When the user's cursors exceed the rectangle, the text will be displayed ONLY selected (mouseover'd) rect.

I can assign id for corrections, but not for text. Code:

svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("id", function(d){ return d.slug; // slug = label downcased, this works }); // each rect has unique id 

However, the same code for my text element on the x axis does not assign id ?!

  svg.append("g") .call(xAxis) .selectAll("text") .attr("id", function (d){ // inspect text element shows no ID. return d.slug; // text doesn't have any id }) .style("text-anchor", "end") .attr("opacity", 0.2); 

How can I assign a unique identifier to my text elements on the x axis? Thanks!

+6
source share
1 answer

The problem is that no data is bound to the x-axis ticks, and therefore d is undefined - you should get an error message when you run your code.

In this particular case, you can use the index to get the corresponding data item, for example.

 svg.append("g").call(xAxis) .selectAll("text") .attr("id", function(d, i) { return dataset[i].slug; }); 

Please note that this will only work if the number of ticks on the axis matches the number of data items.

+13
source

Source: https://habr.com/ru/post/956002/


All Articles