6

Say I want to programmatically insert an additional <tspan> in the <text> element in the following SVG:

<svg width="300" height="500">
    <text x="50" y="100">
        <tspan x="50">one</tspan>
        <tspan x="50" dy="20">two</tspan>
        <tspan x="50" dy="20">three</tspan>
    </text>
</svg>

This can be done with, among other things, pure JavaScript (.appendChild), jQuery (.append), and d3.js (.append). However, although all three methods successfully insert the element, I can only seem to get it to actually display when it's inserted by d3.js:

See reduced case in this fiddle: http://jsfiddle.net/2NLJY/.

The behaviour is consistent across the browsers I've tested: Firefox, Chrome, and Safari (all OS X 10.8).

What is going on here?

serhalp
  • 201
  • 2
  • 7

1 Answers1

11

You can't use createElement to create SVG elements. SVG elements must be created in the SVG namespace so you need to write

document.createElementNS("http://www.w3.org/2000/svg", "tspan");

There is a jquery plugin which adds functionality to jquery allowing svg elements to be created.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • That makes sense. Fixing that has actually just led me back to the actual issue I was trying to investigate here: why are `dy` attributes being ignored (sometimes) when inserting `` elements programmatically? http://jsfiddle.net/2NLJY/1/ This doesn't even look the same in Safari as it does in Chrome and Firefox... – serhalp May 22 '13 at 21:17
  • 2
    @serhalp, that's another question. You should upvote and/or accept the answer above. – mccannf May 22 '13 at 22:43
  • Though useful, it only partially answers my question. Creating the element with createElementNS as stated does not display the `` at the expected location. – serhalp May 23 '13 at 13:19
  • 1
    Why did you change the setAttribute calls? They were correct. Don't use setAttributeNS for attributes other than xlink ones. Although elements are in the SVG namespace, attributes are usually not. – Robert Longson May 23 '13 at 13:37
  • Thanks, that's it. I think I've got some reading to do w/r/t namespaces. One more thing: any idea why Safari ignores the `dy` attribute of a new `` element inserted by d3, after having inserted one via `appendChild`? http://jsfiddle.net/2NLJY/5/ – serhalp May 23 '13 at 15:38