SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    using 'this' inside of jQuery selector

    In this situation 'this' does equal a div with classname of megamenu

    This line worked fine:
    $('div.megamenu p:lt(' + firstHalf + ')').wrapAll('<div class="colone"></div>');

    Until I needed to loop through all div's with classname of megamenu, so now I'm trying to use:
    $(this + ' p:lt(' + firstHalf + ')').wrapAll('<div class="colone"></div>');

    but that's not working.

    What is the proper way to use the 'this' keyword inside of a selector?

    Thanks.

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    http://docs.jquery.com/Core/jQuery#expressioncontext

    Notice the optional context parameter. Normally, you just omit it, and jquery will assume you meant window.document. But you can pass your own object.

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't think I understand, I want to search for 'this' within the context of
    $(this + ' p:lt(' + firstHalf + ')', [this]) ?

  4. #4
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok this worked,
    $('p:lt(' + firstHalf + ')', this)

    Thank You.

    But why did it work? Is this how 'this' needs to be used in all selectors or in my case?

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It depends on what you're trying to do. Both of these are equivalent if that makes more sense to you.
    Code:
    $('p:lt(' + firstHalf + ')', this)
    $(this).filter( 'p:lt(' + firstHalf + ')' )
    If we use a really simple selector example, this is an oversimplification of what happens under the hood.
    Code:
    // $('p')
    function secretJQueryFunction(selector, context) {
        if (context == null) {
            context = window.document;
        }
        return context.getElementsByTagName('p');
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •