Posts Tagged ‘jsp last in a loop’
Replace pseudo-class :last-child using JSTL by determining the loop status
Friday, October 24th, 2008
I wanted to know how you’d figure out when you’d come to the last in a list of items when coding in a jsp. When the number of items vary, there’s no way you can hard code this in.
I wanted to add a :last-child in my webpage so that my list’s last element wouldn’t have a border-bottom, but the rest of the list would. I’m all for progressive enhancement, but sometimes things look so shocking in ie7 and ie6 that you just need to find another (non-css) way to take the border off.
In css, it’s
.keyContact li{border-bottom: 1px solid #000;}
.keyContact li:last-child{border-bottom: none;}
But this doesn’t work in IE7 or IE6. Without it, I get a crappy double line thing, and looks shocking. In my jsp, I’m not sure how many key contacts I’m going to have as it’s running through a loop. But for each item we determine their status:
< c:forEach items="${contacts} var="contact" varStatus="status">
<li class="contact ${status.last ? 'noBorder':">Contact info</li>
</c:forEach>
Of course, you still need to define what noBorder is in the css…
.noBorder{border-bottom: none;}
Now you can delete your li:last-child class in order to keep your css tidy.
This sets a variable so each time it goes through the loop, it knows which is the first, last etc. And when it determines that it is the last element, it will add the class “noBorderâ€, otherwise it will add nothing. (Read it as “is the status last ? (question mark). If yes, add noBorder, otherwise (:) add nothing). FYI this is called a JSTL loop status. Hope that helps!
