2

I am trying to get HTML from a HTML string, I am trying to do this:

var html = '<ul><li>list 1</li><li>List</li></ul>';
console.log($(html).find('ul').html());

But, this return undefined.

What I am trying to do in above code:

actually my html string is returned by an ajax request. And I want to append this html string to a <ul>. so before appending HTML string I want to remove <ul> tags returned from ajax.

Please help me get string without <ul>

xyres
  • 20,487
  • 3
  • 56
  • 85
user007
  • 3,203
  • 13
  • 46
  • 77
  • http://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro might help `:)` – Tats_innit Aug 07 '14 at 08:05

4 Answers4

2

$(html) is itself an object of ul node. You don't need to find it. You can simply use .html() for created object:

$(html).html();

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

The ul is the root node, so you are effectively searching for ul within the ul, which is finding nothing. Instead, use filter() as this will include the root:

var html = '<ul><li>list 1</li><li>List</li></ul>';
console.log($(html).filter('ul').html());

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Just

var html = "<ul><li>list 1</li><li>List</li></ul>";
console.log($(html).html());
levi
  • 22,001
  • 7
  • 73
  • 74
1

you could replace pieces of string where it matches with sub-string you want:

// set string you'd replace
var html = '<ul><li>list 1</li><li>List</li></ul>';
// replace first tag with empty string
var part_res = html.replace("<ul>", "");
// replace last tag with empty string
var res = part_res.replace("</ul>", "");
// print out the new result
console.log(res);
blurstream
  • 429
  • 3
  • 13