Joe.wang
Joe.wang

Reputation: 11793

select elements from a specified html string

All, Say you have a Html string like below. I want to select all the li element from it, and append them to a ul.

var sHtml="<li>..</li><li>..</li><li>..</li><li>..</li><span>xxx</span>";
$("#myUl").append($("li",$(sHtml)));

But this code doesn't work . Is there any way to make it using jquery?

Upvotes: 0

Views: 64

Answers (3)

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

Try this:

var sHtml="<li>..</li><li>..</li><li>..</li><li>..</li><span>xxx</span>";
var htm = $(sHtml);
$("#myUl").append(htm).find("span").remove();

DEMO

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

var sHtml="<li>..</li><li>..</li><li>..</li><li>..</li><span>xxx</span>";
$(sHtml).not('span').appendTo("#myUl");

Fiddle

Upvotes: 1

Rey Libutan
Rey Libutan

Reputation: 5314

If what you are trying to achieve is overwriting part of your current page with html from maybe a page returned by an AJAX call, then give the <ul> an id and do something like

$("#myliID").html($(returnedPage).find("#myliID").html());

Upvotes: 0

Related Questions