Javascript add attribute to XMLSerializer response

Issue

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.

Solution

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>

Answered By – Kaiido

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published