views:

46

answers:

3

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

By reading this article(http://stackoverflow.com/questions/2421719/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  A: 

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

gamue
+1  A: 

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.

alex
good idea! I will use this one if I can't find any solution better:) thanks~
ryan.dingy
+2  A: 

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.

Nick Craver
Understood. Thank you.
ryan.dingy