JSFiddle - React, Tailwind, and code Playground
by Jeremy Banks
HTML
<svg viewBox="0 0 400 100" width="400" height="100">
<text x="20" y="80" font-size="40">
Hello
</text><text x="120" y="80" font-size="60">
World
</text>
</svg>
CSS
svg {
border: 1px solid #123;
}
JavaScript
"use strict"
var root = document.querySelector( "svg" );
var textEls = [].slice.call( root.querySelectorAll( "text" ) );
var i, j, k,
l, m, n;
for ( i = 0, l = textEls.length; i < l; ++i ) {
var firstEl = textEls[ i ],
consecutiveEls = [ firstEl ],
latestEl = firstEl;
while ( i + 1 < l && latestEl.nextElementSibling === textEls[ i + 1 ] ) {
latestEl = textEls[ i + 1 ];
consecutiveEls.push( latestEl );
++i;
}
if ( consecutiveEls.length > 1 ) {
var newContainer = document.createElement( "text" );
newContainer.setAttribute( "x", firstEl.getAttribute( "x" ) );
newContainer.setAttribute( "y", firstEl.getAttribute( "y" ) );
for ( j = 0, m = consecutiveEls.length; j < m; ++j ) {
var oldEl = consecutiveEls[ j ],
oldElAttributes = oldEl.attributes,
oldElChildren = [].slice.call( oldEl.childNodes ),
newEl = document.createElement( "tspan" );
newContainer.appendChild( newEl );
oldEl !== firstEl && oldEl.parentNode.removeChild( oldEl );
for ( k = 0, n = oldElAttributes.length; k < n; ++k ) {
var oldElAttr = oldElAttributes.item( k );
newEl.setAttribute( oldElAttr.nodeName, oldElAttr.nodeValue );
}
for ( k = 0, n = oldElChildren.length; k < n; ++k ) {
newEl.appendChild( oldElChildren[ k ] );
}
}
firstEl.parentNode.replaceChild( newContainer, firstEl );
}
}
// Convert SVG to source via a temporary div, then re-parse.
// I don't know why this is necessary, but it didn't work on all pages without it.
var tmpContainer = document.createElement( "div" ),
tmpSource;
root.parentNode.replaceChild( tmpContainer, root );
tmpContainer.appendChild( root );
tmpSource = tmpContainer.innerHTML;
tmpContainer.innerHTML = "";
tmpContainer.innerHTML = tmpSource;
root = tmpContainer.querySelector( "svg" );
tmpContainer.parentNode.replaceChild( root, tmpContainer );