JQuery: get one of a set of selected items

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

$(".foo")[0].text() does not work.

+7
javascript jquery
source share
3 answers

You want to use .eq(0) , for example:

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

When you execute $(".foo")[0] or $(".foo").get(0) , you get a DOM element , not a jQuery object , .eq() will get a jQuery object that has a .text() method .text() .

+12
source share

Typically, using the syntax, # selector selects one item by the value of the id attribute. Do you have more than one element with the same id attribute value? If so, then you need to fix your HTML. The id attribute values ​​must be unique in the document.

+2
source share

Elements of a jQuery array always return dom elements (not wrapped jQuery elements). You can do something like:

 $ ($ ("# foo") [0]). text ()
+1
source share

All Articles