Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda