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

1357 views jquery
9

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>
    <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>
</div>

answered question
Add a Comment

1 Answer

3

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

$('.two:first-child, .one + .two').each(function() {
  console.log(this.textContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <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>
</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

Please login first before posting an answer.

Ads

Categories