dietervdf
dietervdf

Reputation: 402

conditional loop in jquery selector

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

Answers (3)

Sushanth --
Sushanth --

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.

Check Fiddle

Upvotes: 1

rid
rid

Reputation: 63542

var divs = [];
$('div[status]').each(function() {
    if ($(this).attr('status') === '0') {
        divs.push(this);
    } else {
        return false;
    }
});

Upvotes: 3

lsouza
lsouza

Reputation: 2488

First 3 divs, only with status=0

$('div:lt(3)[status=0]')

Upvotes: 0

Related Questions