Search code examples
javascriptfirefoxsvgsafaritspan

svg - <tspan> inside <text> is not visible in FF and Safari


I am trying to figure out why text inside <tspan> are not visible in FF (v31) and Safari (in Chrome it works). Code which generates texts:

var year_elements_text = document.createElementNS(NS, "text");
year_elements_text.setAttribute('x', String((i * year_all_elements_width) + rect_width + (line_width / 2)) + "px");
year_elements_text.setAttribute('y', String(text_starting_point) + 'px');
year_elements_text.setAttribute('style', 'text-anchor: middle');

year_elements_text.innerHTML = '<tspan>' + String(starting_year + i) + '</tspan>';

g_tl.appendChild(year_elements_text);

Full code is here (jsfiddle).

Without <tspan> in works in Chrome and FF, but doesn't in Safari.

Funny thing: <tspan> example from MDN doesn't work in FF: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/tspan


Solution

  • You shouldn't use innerHTML in an SVG document. Create the tspan and use textContent to set the text...

        var year_elements_text_tspan = document.createElementNS(NS, "tspan");
        year_elements_text_tspan.textContent = String(starting_year + i);
        year_elements_text.appendChild(year_elements_text_tspan);
        g_tl.appendChild(year_elements_text);
    

    http://jsfiddle.net/e834s5L6/