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

156
Visualizações
Inserting rect element inside anchor in svg with javascript doesn't work

I am trying to create a clickable image using svg. Inside the svg I would have multiple rect elements (the parts of the image that I want to be clickable) and around them I would put anchor elements to make them clickable. When I do this using only html, it works without an issue:

  <a href="test.html">
        <rect
                style="fill:#00ff00;stroke-width:0.264583"
                id="rect142"
                width="33.816833"
                height="24.259901"
                x="172.39232"
                y="63.95792" />
        </a>

However, I need to do this dynamically, so I want to use javascript in order to insert the rect element and the anchor. Inserting the element alone works, but when I try to insert it inside an anchor, nothing shows up. Here is my javascript code:

console.log("in")

// make a simple rectangle
var newRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");

newRect.setAttribute("id", "rect604-1");

newRect.setAttribute("x", "172.39232");
newRect.setAttribute("y", "63.95792");

newRect.setAttribute("width", "33.816833");
newRect.setAttribute("height", "24.259901");
newRect.setAttribute("fill", "#00ff00");
newRect.setAttribute("opacity", "0.66");
newRect.setAttribute("fill-opacity", "1");
newRect.setAttribute("fill-rule", "evenodd");
newRect.setAttribute("stroke-width", "0.264583");

var aTag = document.createElement('a');
aTag.setAttribute('href',"test.html");

var svg = document.getElementById("svg12");
console.log(svg)
// append the new rectangle to the svg
aTag.appendChild(newRect);

svg.appendChild(aTag);

//$("#rect604-1").wrap("<a href='https://mail.google.com/mail/u/0/#inbox'></a>");

Any ideas why my code doesn't work?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For creating a link with an svg object, you should use an svg anchor rather than an html anchor. So replace

var aTag = document.createElement('a');

by

var aTag = document.createElementNS("http://www.w3.org/2000/svg", "a")
about 4 years ago · Juan Pablo Isaza Relatório
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