3

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

1 Comment

good idea! I will use this one if I can't find any solution better :) thanks~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.