tags:

views:

33

answers:

3

Within a document, I can use document.getElementById() to get a handle to a particular unique element.

How can I do the same for a group, given as a parameter.

 <g id="right_hook">
  <circle id="wheeltap" r="3" stroke-width="1" />
  <path d="M 0 0 L 200 0 A 5,5 0 0,1 200,20" stroke-width="4" />
 </g>

If I pass this group to a function:

 function some( hook ) {
  var tap1= hook.wheeltap;    // does not work
  var tap2= hook.getElementById("wheeltap);   // does not work

What does?

Reason I do this is I have multiple similar objects which I want to animate in JavaScript. I can of course give each of their subobjects globally unique names (s.a. "right_hook_wheeltap", "left_hook_wheeltap" but that sucks).

A: 

I just looked at this one and think that might use childNodes for the task.

e.g.

getElementById("SVG").childNodes

BTW, have a look at jQuery.SVG plugin (link)

Tzury Bar Yochay
A: 

You can probably use the Selectors API for doing that, if you are fine with requiring rather recent browser releases.

What you want seems to be QuerySelector:

var rh = document.getElementById("right_hook");
var wheel = rh.querySelector("#wheeltap");

I haven't verified that it works with non-unique ID:s though.

Erik Dahlström
+1  A: 

getElementById is trying to find an element by it's unique ID. The DOM specification states:

getElementById... Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

If you have a reference to the hook element you're interested in, then I'd suggest using getElementsByTagName (which returns a collection of elements with the specified tag name):

function some( hook ) {
  var taps = hook.getElementsByTagName("circle");
  var tap1 = taps[0]; // should contain the element you're looking for
  ...
}

Alternatively, as Tzury Bar Yochay says, if jQuery.SVG is an option it would make selectors a lot easier to work with.

dariom