Eschon
Eschon

Reputation: 538

Accessing SVG children in Safari

I load a SVG file with ajax and pass the SVG to a javascript function like this:

var svg = $(xml).find('svg');
map.addSlopeLayer(svg[0]);

Inside the function I access the children of the SVG:

var gs = svg.children;

This works fine in Firefox and Chrome but when I try it in Safari svg.children is undefined.

Is there an error in how I try to access the children or is there another way to access them in Safari?

Upvotes: 1

Views: 401

Answers (2)

Eschon
Eschon

Reputation: 538

I actually found the solution for this a while ago and forgot to post it. As mentioned in the other answer Safari simply does not support the children property for SVG Elements the code I used to work around this is as follows:

var svgChildren = svg.children || svg.childNodes;

for (var i=0; i < svgChildren.length; i++){
  if (svgChildren[i].nodeType == 3) continue;

  //do something with the svg elements
}

Since childNodes also returns text nodes I filter them out using if (svgChildren[i].nodeType == 3) continue;

Upvotes: 2

dev4life
dev4life

Reputation: 11394

In Safari, trying to read children on a SVG Elmeent will always return undefined that is because, sadly, it is not supported. Try using childNodes instead.

Upvotes: 0

Related Questions