0

I just stuck on a problem when trying to select an attribute of a rect object within a svg. This is the rectangle I want to get a value from:

<rect id="2" x="13.761467889908257" y="50" width="49.31192660550459" height="50" fill="rgb(43,0,0)"></rect>

in order to calculate the x-position of another rectangle I need the x-value.

I tried some different ideas like:

svg.selectAll("rect")
   .select("id",2);               // 1st version
   .select("id","2");             // 2nd version
   .select("#2");                 // found in another d3 tutorial -> not working for me

and a lot more. Is there any way to do this?

// If you need more of my code just write it in a comment I wasnt sure how much to write in order to NOT write too much

hGen
  • 2,235
  • 6
  • 23
  • 43

2 Answers2

6

According to HTML 4, id's can't start with a number. HTML 5 did change that, but CSS and d3 still don't really support that. So if it's not necessary, it may be easier to just change the id value to not start with a number. This problem is why the #2 selector isn't working, I think.

If you did want to keep id = 2, you can probably use the attribute selector to do it in one line, like this:

svg.select("rect[id='2']")

You can read what Mike Bostock has to say about id's starting with numbers here.

Then, once you have your selection, just do .attr("x").

rkgibson2
  • 169
  • 6
  • [This question](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) may also help. – Lars Kotthoff Aug 08 '14 at 13:07
  • This should always select the `rect` with `id=2`. Do you need to select different things each time through the loop? – rkgibson2 Aug 08 '14 at 13:12
  • okay i found the mistake I did, this one works within a loop: `svg.select("rect[id='" + i + "']").attr("x")` – hGen Aug 08 '14 at 13:14
  • But there is another problem. If I run the line of code directly within the console everything is working well. If I print it within the code like `console.log( svg.select("rect[id='2']").attr("x") );` I get three lines of output `null``null` and then the x value – hGen Aug 08 '14 at 13:25
  • Is this `console.log` inside a loop? – rkgibson2 Aug 08 '14 at 13:33
  • yes it is, if I use it within the loop I get `null` for every value – hGen Aug 08 '14 at 13:39
  • I think this is a different problem. It may be more helpful to create a new question with more code. I don't feel like there's enough here to tell what's wrong. – rkgibson2 Aug 08 '14 at 13:41
-1

Try calling directly d3.select('#2');

  • tried that also this is what I receive: SyntaxError: Failed to execute 'querySelector' on 'Element': '#2' is not a valid selector. – hGen Aug 08 '14 at 13:04