AGamePlayer
AGamePlayer

Reputation: 7736

How to use d3.js to select an svg element and modify its attr?

I'm a bit new to d3.js and I guess my question is not about any detailed code or data.

here it is:

function selectNodesWithProperty(container, key, value){
  var nodes = d3.selectAll(container).select(function(d, i) { 
    if (value == d[key]) {
      console.log(this); // this works correctly, the element is the one I want.
      this.attr('fill', 'red') 
    }
  });
}
selectNodesWithProperty(".selector", "id", "Blue");

I have two questions:

  1. Is my way the proper way to select the element by data?
  2. Is there any way that I can use d3's attr for the element?

Thanks,

Upvotes: 0

Views: 65

Answers (1)

altocumulus
altocumulus

Reputation: 21578

The most obvious solution is to use selection.filter() to get a subset of the selection containing all the nodes for which the filter is true. You can then use .attr() on the selection returned by .filter() to apply changes to the attribute values of the new subset only.

function selectNodesWithProperty(container, key, value){
  d3.selectAll(container)
    .filter(d => value === d[key]) 
    .attr('fill', 'red') 
}

Upvotes: 3

Related Questions