user3573535 user3573535 - 5 months ago 15
Javascript Question

Elegant way to select html elements 1,2,5,6 ...with unknown number of elements/

Im looking for elegant way to select only divs on left hand side (marked green).
Number of elements is unknown, so i cannot rely on

.eq()
or any other function used for filtering elements.
Thank you for any advice.

enter image description here

Html:

<div class="row">

<div class="col-sm-6">
<div>
</div>
</div>
<div class="col-sm-6">
<div>
</div>
</div>
<div class="col-sm-6">
<div>
</div>
</div>
<div class="col-sm-6">
<div>
</div>
</div>
<div class="col-sm-6">
<div>
</div>
</div>
<div class="col-sm-6">
<div>
</div>
</div>



Answer

For each div... If its left offset is less than the 3rd one...
It has to be selected.

//Find the offset position of the 3rd div
offset3 = $(".col-sm-6").eq(2).offset().left;

$(".col-sm-6").each(function(){
    if($(this).offset().left < offset3){
        SelectIt = $(this).children("div");  // Select the "green" inner div

    // Do something with SelectIt...
    }
});