Reputation: 402
How can I select the first 3 div elements in the following example using jquery?
I want to select the div elements with status = 0 until I encounter any other value.
<div status='0'></div>
<div status='0'></div>
<div status='0'></div>
<div status='1'></div>
<div status='0'></div>
The following example I would only need the first 2 elements
<div status='0'></div>
<div status='0'></div>
<div status='1'></div>
<div status='1'></div>
<div status='0'></div>
Upvotes: 1
Views: 85
Reputation: 55750
Try this
// Get the first div with status
var $first = $('div[status]').eq(0);
// value of first, so that it works with any status condition
// not just status="1"
var initial = $first.attr('status');
console.log(initial);
$first
.nextUntil('div[status!='+ initial +']', 'div[status='+ initial +']')
.andSelf().css('background', 'red');
The first arg for nextUntill
is where to stop the selection, and the 2nd argument which elements to match.
Upvotes: 1
Reputation: 63542
var divs = [];
$('div[status]').each(function() {
if ($(this).attr('status') === '0') {
divs.push(this);
} else {
return false;
}
});
Upvotes: 3