How to get the second match with QuerySelector?

后端 未结 2 1010
栀梦
栀梦 2020-11-30 05:29

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

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

How woul

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 06:29

    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.

提交回复
热议问题