How to get the second match with QuerySelector?

自古美人都是妖i 提交于 2019-12-17 18:34:29

问题


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?


回答1:


Use document.querySelectorAll

document.querySelectorAll('.titanic')[1]



回答2:


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.



来源:https://stackoverflow.com/questions/22902447/how-to-get-the-second-match-with-queryselector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!