jQuery: Trying to write my first plugin, how can I pass a selector to my func?

Posted by Jannis on Stack Overflow See other posts from Stack Overflow or by Jannis
Published on 2010-04-02T20:30:44Z Indexed on 2010/04/02 20:33 UTC
Read the original article Hit count: 341

Hi,

I am trying to start writing some simple jQuery plugins and for my first try if figured I would write something that does nothing else but apply .first & .last classes to passed elements.

so for instance i want to ultimately be able to:

$('li').firstnlast();

So that in this html structure:

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
<ul>
    <li></li>
    <li></li>
</ul>

it would create the following:

<ul>
    <li class="first"></li>
    <li></li>
    <li></li>
    <li class="last"></li>
</ul>
<ul>
    <li class="first"></li>
    <li class="last"></li>
</ul>

What i have written so far in my plugin is this:

(function($) {

    $.fn.extend({
        firstnlast: function() {
            $(this)
                .first()
                .addClass('first')
                .end()
                .last()
                .addClass('last');
        }
    });
})(jQuery);

However the above only returns this:

<ul>
    <li class="first"></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
<ul>
    <li></li>
    <li class="last"></li>
</ul>

It seems that passing only the li into the function it will look at all li elements on the entire page and then apply the classes to it.

What I need to figure out is how i can basically make the function 'context aware' so that passing the above li into the function would apply the classes to those lis inside of the parent ul, not to the first and last li on the entire page.

Any hints, ideas and help would be much appreciated.

Thanks for reading,

Jannis

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about plugins