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

163
Vistas
Javascript add attribute to XMLSerializer response

I am loading SVGs dynamically and want to add an id attribute to the SVG before inserting in the page.

      $.get( "/images/svg/myCodedImage.svg", function( data ) {
          var s = new XMLSerializer();
          $('#mysvg').replaceWith(s.serializeToString(data));
      });

I am trying to avoid having a wrapping element with the id - I want to replace the div with the SVG and give that SVG the same id.

Looked around but could not figure out how.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Add this attribute when you have access to the parsed Document, before converting it to string:

$.get( 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"><rect width="30" height="30"/></svg>', function( data ) {
  // data is a Document, we can use DOM operations on it
  data.documentElement.id = "mysvg";
  var s = new XMLSerializer();
  $('#mysvg').replaceWith(s.serializeToString(data));
});
#mysvg {
  fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mysvg"></div>

If you needed to target a deeper element, with a more complex selector, or to perform more complex edits you could even use jQuery over that Document too:

$.get( 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"><rect width="30" height="30"/></svg>', function( data ) {
  data.documentElement.id = "mysvg";
  // the second argument of `$()` is the context
  $("rect", data).attr({
    stroke: "red",
    x: 2,
    y: 2
  });
  var s = new XMLSerializer();
  $('#mysvg').replaceWith(s.serializeToString(data));
});
#mysvg {
  fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mysvg"></div>

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