views:

319

answers:

4

I'm trying to add borders to the middle column in a three column row. This:

var subcount = $j('#sub > div').size();

Gives me 6, and I'm trying to figure out how to apply a style to the divs in the middle? (in this case, div 2 and div 5)

<div id="sub">
<div>div 1</div> <div>div 2</div> <div>div3</div>
<div>div 4</div> <div>div 5</div> <div>div6</div>
</div>

Is there a way to do that based on the div # and not the id? Like, some sort of foreach loop or something?

+2  A: 

There are lots of ways to do this. It depends on how your data is structured. The brute force way if there are only 6 columns:

$("#sub > div:nth-child(2), #sub > div:nth-child(5)").css("border", "1px solid black");

You can also use an equation with :nth-child:

$("#sub > div:nth-child(3n+2)").css("border", "1px solid black");
cletus
A: 

If those are indeed columns, you'd probably be better off using a real table as it's better suited for tabular data. You also haven't marked your rows, which makes selecting the columns difficult. One way to do it would be this:

var n = 1;
$('#sub > div').filter(function() { return n++ % 3 == 2 });
Reinis I.
A: 

I'll suggest you add some class in code behind, and then apply a clase selector. Or, better, a css style.

If you must use jQuery, cletus solution is just what you want.

MaLKaV_eS
A: 

Since the Array returned by JQuery is zero-indexed, just run something like this for "div" elements 2 and 5:

$(document).ready(function () {
 $("#sub div").filter( function (i) {
  return i == 1 || i == 4;
 }).css("background", "#b4b0da");
});
zdawg