0

with the dom,

document.getElementsByClassName("myClass")[2]

selects the 3rd element of class myClass

in jQuery,

$('.myClass')

gets class myClass but how can I get the 3rd element?!

2 Answers 2

5

You're looking for the :eq() selector:

 $('.myClass:eq(2)')
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of $('.myClass:eq(2)') you can also use $('.myClass').eq(2) or, if you want a DOM element instead of a jQuery element, $('.myClass').get(2)

4 Comments

what's the difference between jquery and dom elements? aren't they the same thing?
No. DOM objects are e.g. those returned by document.getElementById and they are usually host objects (-> they can behave as they want - for example, reading an undefined property could throw an exception - and at least in IE they often do so. additionally extending them or their prototype is dangerous). jQuery objects are pure JavaScript objects which contain one or more DOM objects and metadata (e.g. the selector they used to generate the list)
A good example for DOM vs jquery is retrieving the ID of an element. Using a jQuery object (containing a single DOM object) you'd use obj.attr('id') or obj[0].id (the [] subscript operator returns the contained dom objects); using the DOM object you use obj.id.
wow thanks! I learn more and you solidify what you've learned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.