问题描述:

is it possible to get selection from defined string? For example:

str = "<li>Some text...</li>";

Now I want to get that text between "li" tags, using str variable

as input. I tried something like that, but it didn't work:

$(str + 'li').html();

Any ideas ?

网友答案:

To find the HTML of the inner <li> have this:

var str = "<div>hello</div><ul><li>Some text...</li><li>second item</li></ul>";
var myText = $(str).find("li").html();

(Note that this will give you the inner HTML of the first list item only)

Live test case.

Edit: looks like that for more "complex" things you have to add the HTML to the actual DOM for jQuery to be able to parse it correctly.

To do that, add "dummy" container to the document:

<div id="DummyContainer"></div>

Then have such code instead:

var str = '<div>hello</div><ul><li>Some text...</li><li>second item</li></ul><input type="hidden" name="some_int" value="15" />';
var container = $("#DummyContainer");
container.hide().html(str);
var myVal = container.find("input").val();
alert(myVal);

Updated jsFiddle.

网友答案:

Try just this instead

$(str).html()

http://jsfiddle.net/kSpBp/

As pointed out in the comments, it's worth calling out the difference between html() and text().

text() will "Get the combined text contents of each element in the set of matched elements, including their descendants."

html() will "Get the HTML contents of the first element in the set of matched elements."

In practice this would look like this:

str = "<li>This is so <span>great!</span></li>"
$(str).html() // "This is so <span>great!</span>"
$(str).text() // "This is so great!"
网友答案:
str = "<li>Some text...</li>";
$(str).text();
网友答案:

try:

alert($('<li>Some text...</li>').text());
相关阅读:
Top