score:1

Accepted answer

The way to get the "data" attribute of each polygon is using dataset:

The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM.

In your case, where this is the current DOM element:

this.dataset.price

Pay attention that this will return a string, you may want to coerce it to a number.

Here is the demo, using the value of data-price to fill the polygons:

var svg = d3.select("svg");

var shapes = svg.selectAll("polygon");

shapes.each(function() {
  var thisPrice = +this.dataset.price;
  d3.select(this).attr("fill", thisPrice === 0 ? "#323232" : 
  thisPrice > 1700 ? "#6921dd" : "#2169dd")
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <polygon id="name1" data-price="0" points="30,10 10,50 50,50" />
  <polygon id="name2" data-price="1000" points="80,10 60,50 100,50" />
  <polygon id="name3" data-price="2000" points="130,10 110,50 150,50" />
</svg>

PS: It's not clear what's the colour if the value is above 2500.


Related Query

More Query from same tag