views:

29

answers:

3

There are several elements that are selected by $(".foo"). $(".foo").text() returns the text of each element concatenated together. I just want the text of one element. What is the best way to do this?

$(".foo")[0].text() fails.

UPDATE: I meant the . class selector, not #. Corrected.

+1  A: 

You want to use .eq(0), like this:

$("#foo").eq(0).text()

But as others note, in the case of an ID this should never be the case, a valid case would be on a class, for example:

$(".foo").eq(0).text()

When you do $(".foo")[0] or $(".foo").get(0) you're getting the DOM Element, not the jQuery object, .eq() will get the jQuery object, which has the .text() method.

Nick Craver
+2  A: 

Normally using the # selector syntax selects one element by id attribute value. Do you have more than one element with the same id attribute value? If so, then you need to correct your HTML. id attribute values should be unique within a document.

Greg Hewgill
Given the example is `#foo`, I think this was a question oversight, rather than the actual issue...
Nick Craver
@Nick that is correct.
Rosarch
+1  A: 

The items in the jQuery array always return the dom elements (not the jQuery wrapped elements). You could do something like:

$($("#foo")[0]).text()
jhorback
This is a much more expensive way to go about it :)
Nick Craver