Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to get first element from jQuery class selector?

I feel like I should know this, but you know how with regular JS, you would select the first element in a series like this:

document.getElementsByClassName('class')[0];

?

Well I'm trying to do the same thing with jQuery, butit doesnt seem to be working. I've already tried $('.class')[0], but it doesn't work. What is the proper way to do this?

1 Answer

Steven Parker
Steven Parker
229,644 Points

If you want the first element, then "$('.class')[0]" should indeed work. But if you want the first jQuery object, then use "$('.class').eq(0)" instead.

If you're still having trouble, post the complete code to facilitate analysis.

Thanks Steven