简体   繁体   中英

How to select the nth-child of h2 elements in div

I am using the jquery plugin "hopscotch" Hopscotch

I am also using an "easy responsive tabs" plugin which converts tabs to accordian style to allow for responsiveness.

Hopscotch allows one to write a stepped tutorial that relies on each step having a "target" defined. The targets are defined on the plugin page to be:

target [STRING/ELEMENT/ARRAY] - id of the target DOM element or DOM element itself. It is also possible to define an array of several targets. If an array is provided, Hopscotch will use the first target that exists on the page and disregard the rest.

Therefore I want to set up an array for my target so that it gets the right element regardless of whether the DOM is showing tabs or accordian.

The HTML in accordian looks like this:

<div id="profileFormTabs" style="display: block; width: 100%; margin: 0px;">

<div class="resp-tabs-container">
    <h2 class="resp-accordion" role="tab" aria-controls="tab_item-0">
    // content here
    </h2>
    <h2 class="resp-accordion" role="tab" aria-controls="tab_item-1">
    // content here
    </h2>
    <h2 class="resp-accordion resp-tab-active" role="tab" aria-controls="tab_item-2">
    // content here
    </h2>
</div>

</div>

My first target looks like this:

target: ['profileFormTabs', '.resp-tabs-container > h2'],

This correctly targets the id of profileFormTabs (if they are viewing tabs) and it also correctly targets the first h2 element if they are looking at the DOM and it is in accordian.

My second target is configured as:

target: ['#profileFormTabs ul > li:nth-child(2n)', '.resp-tabs-container > h2:nth-of-type(1)'],

This also works for tabs. BUT, it doesn't work for accordian.

I've tried:

.resp-tabs-container > h2:nth-child(2n)
...
.resp-tabs-container > h2 > h2
...
document.getElementsByClassName("resp-tabs-container").nextSibling
etc

But to no avail.

I can't add id's to all the elements in the accordian without changing the 'easy responsive tabs' plugin which I would rather not do (so it is easy to update when new updates are released).

I've had no luck using jQuery as my target selector. So I wondered if this is possible using purely javascript / css ?

Many thanks

例如,您可以使用document.querySelectorAll('h2:nth-child(1) ul li:nth-child(2)')

A big thanks for the all the answers. I have altered the plugin directly in order to achieve what I needed.

Thanks again :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM