Software Developer

Add CSS Class To nth-child Element With JQuery

This example script is for use with a 3-column layout. It adds the class=”first” to the first column element, and the class=”last” to the 3rd column element.

<script>
jQuery(function() {
    jQuery(document).ready(function() {
		jQuery("div.wrapper > div.grid_4:nth-child(3n+1)").addClass("first");
		jQuery("div.wrapper > div.grid_4:nth-child(3n+3)").addClass("last");
	});
});
</script>

Simple Variation For Wrapped Rows

If you have a grid layout that has each row wrapped with a wrapper element, then you only need to add a CSS class of ‘first’ or ‘last’ in one instance per row. In this case, you can use a simpler :nth-child equation:

<script>
jQuery(function() {
    jQuery(document).ready(function() {
		jQuery("div.row-wrapper > div.grid_4:nth-child(1)").addClass("first");
		jQuery("div.row-wrapper > div.grid_4:nth-child(3)").addClass("last");
	});
});
</script>

Note that this javascript only works if you include jQuery.

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]