문제

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?

도움이 되었습니까?

해결책

Use document.querySelectorAll

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.

Refer to this quick CodePen to play around this approach: https://codepen.io/adamchenwei/pen/RwZvQvW?editors=1111

NOTE: It is not accurate to use n-th-child against classes among child elements that have different class names. Plz do not do that. I would suggest to find alternative method (which I am not aware at this time) ref: nth-child doesn't respond to class

a use case example WILL NOT WORK with n-th:child: https://codepen.io/adamchenwei/pen/MWQMObL

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top