-1

I have this table-like structure in my code. Is there a pretty way to select the first 'half' of the spans contained within the div?

<div> 
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

I could do the typical div - children, then count and divide by two. But I was wondering if there was a selector based on a child interval position. Like .find("span[0-4]")

Gleiemeister 2000
  • 731
  • 4
  • 9
  • 23

1 Answers1

3

I'd suggest using the .slice() method. Retrieve the total number of span elements by accessing the .length property, and then divide that in half:

var $el = $('div span');
$el.slice(0, Math.ceil($el.length / 2)).addClass('half');
div span {
    display: inline-block;
    height: 20px;
    width: 100%;
    border: 2px solid;
}
.half {
    border: 2px solid #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> 
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

In order to access the last half, use either of the following instead:

$el.slice(Math.ceil($el.length / 2), $el.length)
$el.slice(-Math.ceil($el.length / 2))
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304