Skip to content Skip to sidebar Skip to footer

Jquery Selector For First Row Of Inline-block Divs

I have some divs with display: inline-block; and I have to select first row of divs and set them for example different border color and I need to do it in javaScript (jQuery). Here

Solution 1:

You have to check what elements are in the first row, and mark those. A way to do this would be fiddle

This code makes the assumption that the first element is first in a row (which is always true), and checks which elements have the same offset top, it then applies a borderColor change to them

var top;
$('.container .item').each(function(i){
    var thistop = $(this).offset().top;
    if (i==0){
        top = thistop;
    }
    if (top==thistop){
        $(this).css({borderColor:"purple"});   
    }
});

Note that in a real life application you'd use a event handler on window resize to run this again on window resize.

I made a separate fiddle to do the event handler version. This requires wrapping above code in a function, and changing the functionality a bit to add/remove classes instead of just adding css (since adding and manually removing css get's messy). Fiddle can be found here.

So instead of adding css, it adds/removes a class

markrow = function(){
        $('.container .item').each(function(i){
        ...
        if (top==thistop){
            $(this).addClass('special');
        }else{
            $(this).removeClass('special');
        }
    });
}
markrow();
$(window).on('resize',markrow);

With special being a css class that changes the border color

.special {
    border-color:purple;
}

Solution 2:

You may use vanilla CSS Selector for this in jquery. Assuming that you have a grid of 3 X 3.

$( ".container .item:nth-child(3n + 1)" ).css( "border-color","black" );

Solution 3:

$('.item').eq(0).addClass('special-border');

.special-border {
    border-color: #00f;
}

http://jsfiddle.net/8193xgfn/9/

Solution 4:

you can get the width of your container which has a css-style named "container" by $(".container").width,

and then you can calculate how many divs can be put in the first row,and put it in a variable like firstrow_divNums.

now use $(".calculate").children() to get the child-divs,

finally use "for" loop from $(".calculate").children().eq(0) to $(".calculate").children().eq(firstrow_divNums) ,

and now you can do what you want like adding css-style to any elements.

Post a Comment for "Jquery Selector For First Row Of Inline-block Divs"