Can I select multiple 'first-of-type's in a set of siblings via jQuery?

1362 views jquery

In this example, is there a way to use jQuery/js to select the first of each group of '.two' divs among siblings (i.e., a, d and i)?

    <div class='two'>a<div>
    <div class='one'>b<div>
    <div class='one'>c<div>
    <div class='two'>d<div>
    <div class='two'>e<div>
    <div class='two'>f<div>
    <div class='one'>g<div>
    <div class='one'>h<div>
    <div class='two'>i<div>
    <div class='two'>j<div>

answered question

1 Answer


One option is to combine the selectors .two:first-child and .one + .two:

$('.two:first-child, .one + .two').each(function() {
<script src=""></script>
    <div class='two'>a</div>
    <div class='one'>b</div>
    <div class='one'>c</div>
    <div class='two'>d</div>
    <div class='two'>e</div>
    <div class='two'>f</div>
    <div class='one'>g</div>
    <div class='one'>h</div>
    <div class='two'>i</div>
    <div class='two'>j</div>

(also note that you probably want to change the <div>s at the end of each line to </div> - you want to end the divs, not start a new div, at the end of a line)

posted this

Have an answer?


Please login first before posting an answer.