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

165
Visualizações
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 Respostas
Responde à pergunta

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