开发者

jQuery: Get one of a set of selected elements

There are several elements that are selected by 开发者_如何学JAVA$(".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.


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

$(".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.


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜