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

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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