3

Making an object (or something?) from a string:

var thing = $.parseHTML("<h1>Some HTML</h1>"); // i.e., from $("#something").html()

Converting it back into a string?

$(thing).html(); // doesn't work
undefined
$(thing).get(0).outerHTML; // doesn't work
undefined
$(thing).outerHTML; // doesn't work
undefined
$(thing).get(0).html(); // doesn't work
undefined

What's the inverse of $.parseHTML()? I just want to modify some HTML and put it back where I got it.

Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111

2 Answers2

1

To convert jQuery object to string, you can use .prop('outerHTML'), like:

var thing = $.parseHTML("<h1>Some HTML</h1>");
var original = $(thing).prop('outerHTML');

console.log( original );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • Seems like a roundabout way to do it. Why not `thing[0].outerHTML` – H77 Apr 06 '18 at 07:00
  • Well, we dont really know OP's whole code. This can be used if the object is already a jQuery object which I stated on my answer. There are always multiple ways to skin the cat :) – Eddie Apr 06 '18 at 07:20
  • Wonder if this has changed in newer versions of jquery. Does not work for me - $(thing).prop('outerHTML'); returns undefined – bikz Oct 14 '22 at 17:02
1

Check its outerHTML

console.log( thing[0].outerHTML );

Demo

var thing = $.parseHTML("<h1>Some HTML</h1>"); 

console.log( thing[0].outerHTML );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
gurvinder372
  • 66,980
  • 10
  • 72
  • 94