简体   繁体   中英

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.

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> 

You need to convert it to a DOM object, do the text modification and then back to a string

 var compiled = '<div><div id="header-content">Test</div></div>'; alert($(compiled).find('#header-content').html()); //1-First convert it to a DOM element var domhtml = $.parseHTML( compiled ); //2-Second do the text replacement $(domhtml).find('#header-content').html('Woot'); alert($(domhtml).find('#header-content').html()); //3-Convert back to string the DOM element var newCompiled = $(domhtml).html(); alert(newCompiled); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM