1

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 ?

1
  • $(str + 'li') would result in $('<li>Some text...</li>li').... not sure what you wanted to accomplish with that. Either you pass HTML and let it parse by jQuery, or a selector (which seems what you wanted to do), but not both. Commented Nov 9, 2011 at 14:40

4 Answers 4

3

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!"
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Actually my "real world" situation is more complex. I have nested input hidden field and I have to get its value. More complex live test - jsfiddle.net/xyZY8/1
1
str = "<li>Some text...</li>";
$(str).text();

Comments

0

try:

alert($('<li>Some text...</li>').text());

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.