Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!