ryan.dingy
ryan.dingy

Reputation: 45

Jquery: How can I Get/Set html of a String Variable by using Jquery Selectors?

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

Upvotes: 3

Views: 6044

Answers (3)

Nick Craver
Nick Craver

Reputation: 630429

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.

Upvotes: 4

alex
alex

Reputation: 490263

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.

Upvotes: 1

gamue
gamue

Reputation: 161

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

Upvotes: 1

Related Questions