Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert jQuery object to HTML

I'm trying to take a string in javascript, parse and replace an item within the HTML and then cast it back to a string. I cannot for the life of me figure out how to turn the new jQuery object back to HTML.

var compiled = '<div><div id="header-content">Test</div></div>';
$(compiled).find('#header-content').html('Woot');
var newCompiled = $(compiled).html();
//Need newCompiled to be '<div><div id="header-content">Woot</div></div>'

Please help.

like image 282
FAtBalloon Avatar asked May 30 '26 11:05

FAtBalloon


1 Answers

You are modifying the dom elements created by jQuery, but is not storing the reference to the created element

var compiled = '<div><div id="header-content">Test</div></div>';

var $tmp = $('<div />', {
  html: compiled
})

$tmp.find('#header-content').html('Woot');
var newCompiled = $tmp.html();

snippet.log(newCompiled)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

If you are just trying to add the newly compiled element to dom, then there is no need to create a tmp div, instead you can

var compiled = '<div><div id="header-content">Test</div></div>';

var $tmp = $(compiled)

$tmp.find('#header-content').html('Woot');

$tmp.appendTo('body')
div {
  border: 1px solid red;
  padding: 5px;
}
#header-content {
  background-color: lightgrey
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
like image 63
Arun P Johny Avatar answered Jun 01 '26 00:06

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!