34

The following statement gives me the first element with the class titanic

element = document.querySelector('.titanic');

How would I retrieve the second element with the same class?

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Nicky Smits
  • 2,406
  • 3
  • 17
  • 23
  • https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll – Phil Apr 07 '14 at 02:01
  • 1
    `querySelectorAll` returns a collection instead of a single element. The results are returned in document order, which is defined as a depth-first ordering. – cookie monster Apr 07 '14 at 02:02

2 Answers2

57

Use document.querySelectorAll

document.querySelectorAll('.titanic')[1]
Phil
  • 128,310
  • 20
  • 201
  • 202
  • This would work. But wouldn't make me able to change it's values directly, just read them. Because it is a static nodelist, instead of a live nodelist. Also, static nodeLists take more time to produce than live nodelists. Is there an alternative? – Nicky Smits Apr 07 '14 at 02:09
  • 1
    @NickySmits You can still make changes to the elements found. A static node list just means that it does not change when the document is changed (elements added / removed) – Phil Apr 07 '14 at 02:10
  • I tried. But i was not able to change the innerHTML with the static node, while it was possible with a live node. – Nicky Smits Apr 07 '14 at 02:13
  • 1
    @NickySmits Then you're doing something else I'm not aware of - http://jsfiddle.net/ZQZhX/ – Phil Apr 07 '14 at 02:16
  • Holy crap! It does work! Thx bro. I did the exact same thing and it didnt work, but appearantly it was just some random fault. Well, this helps me a great deal. Do you perhaps know any way to make this a live nodelist too? – Nicky Smits Apr 07 '14 at 02:22
25

You don't necessarily need querySelectorAll for picking second element and the question is to use querySelector API. You can utilizing the power of CSS in the selector.

For example you can do:

document.querySelector('.titanic:nth-child(2)')

to pick second element. NOTE: the count starts at 1, not 0.

halfer
  • 18,701
  • 13
  • 79
  • 158
Ezeewei
  • 6,347
  • 7
  • 50
  • 98