Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get one of a set of selected elements

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.

like image 941
Nick Heiner Avatar asked Jun 06 '10 00:06

Nick Heiner


People also ask

Which jQuery method is used to set one or more style properties for selected elements?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements.

What does the jQuery wrap () function do?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

How do you select an element with a particular class selected?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.

What is the use of toggle () method in jQuery?

jQuery toggle() Method The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden.


2 Answers

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.

like image 156
Nick Craver Avatar answered Sep 20 '22 16:09

Nick Craver


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.

like image 21
Greg Hewgill Avatar answered Sep 21 '22 16:09

Greg Hewgill