Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

344
Visualizações
How to place text over a SVG shape with JavaScript, React, and HTML?

I'm using a combination of .createElementNS() and .appendChild() functions to add circle elements and their SVG parent elements to the DOM. However - when I create a sibling text element relative to the circle element, a text node is create in the DOM but isn't displayed. How do I get my text node to display over my circle element SVG?

Here's what my JavaScript creates followed by the SVG that's rendered in the DOM.

document.addEventListener('DOMContentLoaded', () => {
  let digitKeys = 10;
  for (let i = 0; i < digitKeys; i++) {

    const textNode = document.createTextNode(i); // last/deepest child

    const textElement = document.createElement('text'); // first/deepest parent
    textElement.setAttribute('color', 'white');
    textElement.setAttribute('z-index', 50);
    textElement.setAttribute('alignment-baseline', "middle");
    textElement.setAttribute('text-anchor', "middle");
    textElement.setAttribute('x', 8);
    textElement.setAttribute('y', 2);
    textElement.setAttribute('font-size', 50);
    textElement.appendChild(textNode); // append deepest child to first parent

    const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle') //svg elements require createElementNS() (NS = namespace) instead of createElement();
    circle.setAttribute('class', 'digitKeys');
    circle.setAttribute('cx', 50)
    circle.setAttribute('cy', 50)
    circle.setAttribute('r', 33)
    circle.setAttribute('fill', 'steel') // sibling of first parent
    circle.appendChild(textElement);
    console.log(circle)
<svg id="circlesSVG" width="100" height="100">

  <circle class="digitKeys" cx="50" cy="50" r="33" fill="steel">

    <text color="white" z-index="50" alignment-baseline="middle" text-anchor="middle" x="8" y="2" font-size="50">
      0
    </text>
  </circle>
</svg>

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda