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?
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?
document.querySelectorAll('.titanic')[1]
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
.