0

I convert a string of HTML into an object so I can manipulate like this

var HTMLStr = "<div><span>TESTING</span></div><h1>HEADING</h1><div class='two'>sjdufhs</div>";
var HTMLDom = $(HTMLStr).find("h1").remove();
var newHTMLStr = ???

Question: How can I convert the HTMLDom back into a string after manipulation?

I have tried the following: https://stackoverflow.com/a/652771/3758078 But that only converts the first element found, and not the rest. Especially if theres no element containing all other elements.

Community
  • 1
  • 1
  • Only the first element found and not the rest. Sounds like you need a loop. – Charlie Fish Jul 15 '16 at 22:13
  • What is your current output from using that question, and what did you expect? – 4castle Jul 15 '16 at 22:20
  • The output is: '
    ' as a string and not the other elements. The example HTML string above is a simplified version. I expected an HTML string identical to HTMLStr variable, but with the

    element removed.

    –  Jul 15 '16 at 22:26
  • 2
    I was about to answer, but then found that my answer already exists here: [jQuery remove tag from HTML-String](http://stackoverflow.com/questions/12109946/jquery-remove-tag-from-html-string) – 4castle Jul 15 '16 at 22:55

1 Answers1

2

You need to save the result of parsing the HTML into a variable, so you can get its HTML after modifying it.

You also need to wrap the original HTML in another element, because getting the HTML later with .html() will only return the HTML of the first element in the collection.

var HTMLStr = "<div><span>TESTING</span></div><h1>HEADING</h1><div class='two'>sjdufhs</div>";
var DOM = $('<div>' + HTMLStr + '</div>');
DOM.find("h1").remove();
var newHTMLStr = DOM.html();
console.log(newHTMLStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Barmar
  • 741,623
  • 53
  • 500
  • 612