jQuery plugin to add a CSS class to last-child DOM elements

This has been bugging me for ages. IE < 9 does not support the CSS3 last-child pseudo class. I’ve created a _very_ simple jQuery plugin to add a CSS class “last-child” to the element that is the last child of a DOM element.

It performs this recursively, so it’ll apply the class to the last child of an element as well as to the last child of all it’s children…and so on and so forth.

It’ll perform this on each of the set of matched elements in a jQuery object. So you can have it traverse the whole, of your page by providing a jQuery object with the <body> element in it, or you can pick and choose DOM elements to apply the plugin to for efficiency. For instance, you might only need the "last-child" class to be applied to the last child of an unordered or ordered list:

    $('body').lastChild(); // Applies to all elements attached to the document.body
    $('ul, ol').lastChild(); // Applies to all elements in an unordered or ordered list

By default, the plugin applies the CSS class to a restricted set of DOM element types. You can specify the types of DOM elements to apply the class to by passing an options object to the function. In this way you can also specify the name of the CSS class that will be applied:

    $('ul, ol').lastChild({
        tags:['li'], // Only elements with the tag name 'li' will have the class applied to them
        cssClass:'ie-last-child' // The CSS class name will be 'ie-last-child'
    });

For super shorthand, you can simply pass a string to the lastChild function – which it presumes to be the CSS class you want to use:

    $('ul, ol').lastChild('ie-last-child');

You can download the plugin here.

Note, while I created this plugin to get around my IE problem, it is not built specifically for IE. If you only want IE to receive these classes, you’ll probably want to do something like:

    if($.browser.msie) {
        $('body').lastChild();
    }

…but obviously preferably using Modernizr:

    if($('.ie6, .ie7, .ie8').length) {
        $('body').lastChild();
    }

Enjoy!

3 thoughts on “jQuery plugin to add a CSS class to last-child DOM elements

  1. Women who took part in a supervised exercise program during adjuvant treatment for breast cancer had better cardiovascular function than women who did not participate in the program buy priligy reddit If you don t have PCOS then either medication should be okay

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>