Fred J. Fred J. - 3 months ago 18
HTML Question

Convert jQuery element to html string

This JS code tries to modify the raw html. It does that by converting the html to jQuery element, does the modifications on the jQuery element then the part which is not working is converting back to raw html string.

Since

.html()
will not work with xml as indicated in the docs

How can it convert the jQuery back to raw html string? Thanks



let jQ = $($.parseHTML(raw_html));
//modify jQ to heart content
console.log(jQ.html()); //<-- undefined


The raw_html


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
//...

</html>


edit

Output of
console.log($.parseHTML(raw_html));


enter image description here

Answer

Do var a = $('<div>').append(raw_html);

//do modifications to variable a

$(a).html() will display the correct html

NOTE this will strip head and other tags as discussed here

heres a plnkr

Comments