JQuery: How can I get / set the html of a String variable using jquery selectors?

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

After reading this article (how to apply jQuery element selection to a string variable , I can successfully get elements from a string that stores HTML text. For instance:

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();

swill be <li>some text 2</li>. This is what I want.

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

I set s= new html line, but htmlstrnot changed.

thank

+3
source share
3 answers

You can do it like this in a little 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);

/ , .

+4
+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 embed HTML in the DOM, add a new list item, and then return the resulting HTML code and delete the added items.

+1
source

Source: https://habr.com/ru/post/1737109/


All Articles