Bartosz Śledź Bartosz Śledź - 5 months ago 17
Javascript Question

For each before selected div in Jquery

HTML

<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
<div id="id3"></div>
<div id="id6"></div>


I'm selecting
id3
and I want to make a loop for
id1
,
id5
and
id4
.
How can I do it?

Answer

Presuming you want to do some action on every div prior to the selected one you want something along the lines of:

$('#id3').prevAll().each(function() {
    var item = $(this);
    //item will be id1, id5 and id4 respoectively.
});

Bear in mind that if you simply want to do something to all these items then you probably don't want the each. So for example:

$('#id3').prevAll().css( "background-color", "red" );

It's also a good iea to make your code more reilient and check for it not returning anything:

var allPrevious = $('#id3').prevAll();
if (allPrevious){
   allPrevious.each(function() {
        var item = $(this);
        //item will be id1, id5 and id4 respoectively.
    });
}

Thurns them all read. Basically the JQuery docs on prevAll() cover this with examples, etc.

Given a jQuery object that represents a set of DOM elements, the .prevAll() method searches through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements; the elements are returned in order beginning with the closest sibling.