html - After creating a <text> element with javascript, why can't I getBBox? -
i have script adds <text>
element markup, inside existing <svg>
. running getbbox()
on new element gives me error. if include <text>
in markup begin , run equivalent script, getbbox runs without problems. dom not treating js-built <text>
text element… missing "the thing written '<text>' in fact <text>
" step?
function works() { console.log('start "works"') var svgelem = document.queryselector('.works'); var textelem = svgelem.queryselector('text'); var textbbox = textelem.getbbox(); console.log(textbbox); console.log('end "works"') } works(); function doesntwork() { console.log('start "doesntwork"') var svgelem = document.queryselector('.doesntwork'); var textelem = document.createelement("text"); textelem.appendchild(svgelem.firstchild); svgelem.appendchild(textelem); console.log('"doesntwork" breaks after this'); var textbbox = textelem.getbbox(); // breaks script console.log(textbbox); console.log('end "doesntwork"') } doesntwork();
<svg class="doesntwork"> not working </svg> <svg class="works"> <text> working </text> </svg>
less generic second part:
in full project, i'm turning
<div class="target">content</div>
into
<div class="target"><svg><text>content</text></svg></div>
using js create <text>
, <svg>
. idea basically
var targetelems = document.queryselectorall('.target'); (var = 0; < targetelems.length; ++i) { // each target var targetelem = targetelems[i]; var textelem = document.createelement("text"); // build <text> while (targetelem.firstchild) // put target's content (which include child elements) in <text> textelem.appendchild(targetelem.firstchild); var svgelem = document.createelement("svg"); // build <svg> svgelem.appendchild(textelem); // put <text> in <svg> targetelem.appendchild(svgelem); // put <svg> in target var textbbox = textelem.getbbox(); // want able <text>'s bbox (this has breaking error) console.log(textbbox); }
do have add signal @ each step - "this <text>
, <svg>
"?
or going whole thing wrong / there smarter way turn .target > [content]
.target > svg > text > [content]
?
you should able use: createelementns.
document.createelementns(string namespaceuri, string qualifiedname)
.where:
namespaceuri = "http://www.w3.org/2000/svg" name = "text"
something this:
function worksnow() { console.log('start "worksnow"') var svgelem = document.queryselector('.worksnow'); var textelem = document.createelementns("http://www.w3.org/2000/svg", "text"); // changed textelem.appendchild(svgelem.firstchild); svgelem.appendchild(textelem); var textbbox = textelem.getbbox(); // no longer breaks script! console.info(textbbox); // gets svgrect data. console.log('end "worksnow"') } worksnow();
<svg class="worksnow"> works now! </svg>
so, in console, you'll this:
Comments
Post a Comment