29

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?

2
  • 1
    try d3.select("#" + i) Dec 6, 2013 at 2:47
  • 2
    It gives me these errors: Uncaught SyntaxError: Failed to execute query: '#56' is not a valid selector.
    – Milad
    Dec 6, 2013 at 2:50

1 Answer 1

47

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").

4
  • any idea how to do this where attribute < or > then a certain value May 12, 2014 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 7, 2016 at 20:37
  • The docs moved. Permalink to the last version is Docs @ commit 434aee. Mar 30, 2017 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 2, 2019 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.