I am new to d3. I have something defined like this:
node = node.enter().append("circle") .attr('id', function(d){ return d.id; }) .attr("class", "node") .on('mouseover', mouseover_node) .on("click", nodeClick);
Now in function nodeClick I want to access a node (or circle) with a special id. I am looking for something that I could use like this:
for(var i=0;i<maxId;i++) { d3.select(the node with id = i).do....
Does anybody know how I can do this?
attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
From the DOM, D3 selects the body element and returns a reference of the selection to the next method in the chain which is append(). From the filtered content that it received, the append() method works only on the reference element(s) it received. In this case, it is the body element.
Your problem is that id
s and name
s must begin with a letter. So modify your code to prepend a string to each id
, e.g.
.attr('id', function(d){ return 'name' + d.id; })
Then, you can select a given node by using d3.select( '#name' + i )
. From the docs on D3 selections:
... you can select by tag ("div"), class (".awesome"), unique identifier ("#foo"), attribute ("[color=red]"), or containment ("parent child").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With