innerHTML in SVG

Hi guys.

I tried to find something about innerHTML in SVG file, but it was in vain. There is no innerHTML at all in SVG. I must confess, I tried to use textContent, but didn’t work. Ashey, it’s put my string as text in tree document. Ok, now I’ll show my workaround, pro and cons.

First of all, innerHTML is a property defined by xhtml, which means, only a player that supports html can handle this. Safari, Firefox, can (I tested), but Ms IE, Ad SVG Viewer, J2ME and others, I don’t know. Please, test and post in comment below.

We’re going to create a function to make this for us. The technique, is simples. We create a ‘div’ element, then put our svg string inside this div. After that is simple to return or string as elements.

function stringToDOM( value )
{
// To create a div inside a svg document, we need set the NS (namespace). //
var d = document.createElementNS( “http://www.w3.org/1999/xhtml”, “div” );

// Add a svg tag and inside this, put the value argument //
d.innerHTML = “<svg:svg xmlns:svg=\”http://www.w3.org/2000/svg\”>” + value + “</svg:svg>”;

// return one node or an array of them //
return a.firstChild.childNodes.length == 1 ? a.firstChild.childNodes[0] : a.firstChild.childNodes;
}

Observe that we put the value inside a svg element. We MUST specify the namespace in all steps, including the value received. For example:

var rect = stringToDOM( ‘<svg:rect x=”10″ y=”10″ width=”100″ height=”100″ fill=”red” />” );

If you forget to put ‘svg:name’ it will not works.

Thanks.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Sair / Alterar )

Imagem do Twitter

You are commenting using your Twitter account. Sair / Alterar )

Foto do Facebook

You are commenting using your Facebook account. Sair / Alterar )

Connecting to %s

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.