27

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?

Milad
  • 451
  • 1
  • 5
  • 11

1 Answers1

46

Your problem is that ids and names 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").

Community
  • 1
  • 1
mdml
  • 19,981
  • 8
  • 48
  • 61
  • any idea how to do this where attribute < or > then a certain value – mireille raad May 12 '14 at 23:08
  • @mireilleraad On the lowest level, you can select all elements you are interested, run a `for` loop and pick out those elements that qualify your criteria. for instance: `var all_elements = $('.line'); var line_num_big = []; for (var i = 0; i < all_elements.length; i++) { if (parseInt ($(all_elements[i]).attr('id') > 1000) { line_num_big.push(all_elements[i]); }`. Pardon the formatting, writing all in one line is not fun. – benjaminz Apr 07 '16 at 20:37
  • The docs moved. Permalink to the last version is [Docs @ commit 434aee](https://github.com/d3/d3/wiki/Selections/434aeefd362e0b132257977a0ef7af4133544919). – luckydonald Mar 30 '17 at 15:03
  • 1
    `d3.select("[id='" + i + "']")` looks useful but is there a way to specify multiple conditions? Say id = 1 and sid = 2? – Awn Jul 02 '19 at 10:40