Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Append a <tspan> into svg text element with vanilla javascript

I'm trying to use javascript to create a bunch of SVG elements. I've got a lot of it working, and the below code is all working except for one part...

function newPerkLabel (x, y, name) {
    var newLabel = document.createElementNS("http://www.w3.org/2000/svg", "text");
    newLabel.setAttribute("font-size", "0.8em");
    newLabel.setAttribute("x", x);
    newLabel.setAttribute("y", y+25);
    newLabel.setAttribute('fill', '#000');
    newLabel.setAttribute("text-anchor", "middle");
    newLabel.textContent = name;
    svgBox.appendChild(newLabel);
}
function newPerkLabel2 (x, y, name, parent) {
    var newLabel = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
    newLabel.setAttribute("font-size", "0.8em");
    newLabel.setAttribute("x", x);
    newLabel.setAttribute("y", y+25);
    newLabel.setAttribute('fill', '#000');
    newLabel.setAttribute("text-anchor", "middle");
    newLabel.textContent = name;
    parent.appendChild(newLabel);
}
function drawSkillTree(skillTree) {
//Get SVG area
let svgBoxRect = svgBox.getBoundingClientRect();

//Run through each perk in skillTree
for (let i = 0; i < activeSkillTree.perks.length; i++) {

    let perk  = activeSkillTree.perks[i];
    let curXPos = perk.xPos / 100 * svgBoxRect.width;
    let curYPos = perk.yPos / 100 * svgBoxRect.height;

    //Create perk labels
    let perkName = perk.name;
    if (perkName.indexOf('<br>') != -1) {
        let perkNameLines = perkName.split('<br>');
        let line1 = newPerkLabel(curXPos, curYPos, perkNameLines[0]); 
        newPerkLabel2(curXPos, curYPos, perkNameLines[1], line1);

    } else {
        newPerkLabel(curXPos, curYPos, perkName); 
    }

}

}

I'm trying to have the option of adding in line breaks, and to do that, I need a <tspan> element into the svg <text> element. How would I go about doing that?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!