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>

1

4 Answers 4

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

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

Comments

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

Comments

1

Just

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

Comments

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

Comments

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.