Home > front end >  Javascript add attribute to XMLSerializer response
Javascript add attribute to XMLSerializer response

Time:01-05

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.

CodePudding user response:

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>

  •  Tags:  
  • Related