Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript JQuery and ‘this’ keyword

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #28278
    NightArcher
    Member

    OK, so I know that the ‘this’ keyword belongs to the owner of the function it’s in so…
    In this example:

    Code:
    $(‘ol li’).each(function() {
    if(this.hasClass(‘prev’))
    {
    this.addClass(‘test’);
    }
    });

    ‘this’ refers to the current element selected by

    Code:
    $(‘oly li’).each()

    Right? or am I crazy?
    Also should

    Code:
    this.addClass(‘test’)

    actually be

    Code:
    $(this).addClass(‘test’)
    #72039
    Chris Coyier
    Keymaster

    $(this) becomes a jQuery set, and thus is able to have jQuery functions performed on it. At least that’s how I understand it. With "this" by itself, that’s a reference to the element, and you have direct access to DOM stuff like this.offsetLeft or whatnot, but you don’t get all the fun jQuery abilities (like chaining, e.g. $(this).addClass("yeah").slideDown(); ) I’m not even sure if this.addClass(); will work… did you try it?

    #72042
    NightArcher
    Member

    Yea, I’ve tried both ‘this.addClass()’ and ‘$(this).addClass()’ and neither give the desired result… :(

    #72045
    NightArcher
    Member

    WOW… I’m sorry I realized when I was looking at stuff, the code above doesn’t even attempt to do what I want it to, and if I wanted to do what it did I would just do

    Code:
    $(‘li.prev’).addClass(‘test’);

    Thanks anyway Chris

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.