Jquery: How can I Get/Set html of a String Variabl

2019-05-10 00:18发布

问题:

Firstly, sorry for my English (I'm from China).

By reading this article(how to apply jQuery element selection to a string variable), I can successfully get Elements from a String which stores HTML text. For example:

var htmlstr = "<div><ul><li>some text 1</li></ul></div><div><ul id=list><li>some text 2</li></ul></div>";
var s = $('ul#list', $(htmlstr)).html();

s will be <li>some text 2</li>. It's what I want.

But the question is, if I want to add another LI element to this string (htmlstr) how can I do?

I set s = new html string but htmlstr doesn't change.

Thanks

回答1:

You can do it like this in a bit less code:

var htmlstr = "<div><ul><li>some text 1</li></ul></div><div><ul id='list'><li>some text 2</li></ul></div>";
htmlstr = $("<div />").html(htmlstr).find("ul#list").append("<li>New Item</li>").end().html();
alert(htmlstr);

Just change that find selector and/or the append text if you want to stick the element in a different place.



回答2:

I think it's possible to select the ul and append the new li, with the following method: http://api.jquery.com/append/



回答3:

I'm not sure if this is the best way but what about this:

var htmlstr = "<div><ul><li>some text 1</li></ul></div><div><ul id=list><li>some text 2</li></ul></div>";
// make sure you choose a suitable Id here that won't conflict
$('body').append('<div id="test" style="display: none;">' + htmlstr + '</div>');

$test = $('#test');

$test.find('ul').append('<li>new</li>');

htmlstr = $test.html();
// clean up the DOM
$test.remove();


var s = $('ul#list', $(htmlstr)).html();

Basically, you insert the HTML into the DOM, append the new list item and then get the resulting HTML back and remove the elements you added.