Forums

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

Home Forums JavaScript Dumbfounded by THIS

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #148942
    Rugg
    Participant

    Hi there,

    I cant quite wrap my head around the output of the following two javascript samples.

    The first example executes properly using ‘this’ as a selector, however if I use the actual class name that ‘this’ refers to, it doesn’t execute properly.

    Here are the 2 examples for clarification…

    First (working): http://jsfiddle.net/W7kDf/
    Second (not working): http://jsfiddle.net/33sZG/

    Any ideas?

    #148943
    Paulie_D
    Member

    The second is executing properly but it starts at the first div each time…so the function finds a div with a class of .color…it also has a class of .red…so it stops.

    At least that’s the way I understand it.

    #148945
    Paulie_D
    Member

    Ok…perhaps I missed it…I’m no expert in JS.

    The second is executing properly but if the function finds any div with a class of .color…and it also has a class of .red… it stops.

    #148957
    TheDoc
    Member

    Here’s how I would write it out: http://jsfiddle.net/33sZG/3/

    The reason why it was always returning as ‘Red’ was because you’re using the same class selector.

    $('.color').hasClass('red');
    

    That will always return true because there is a div with a class of color that also has a class of red.

    #148961
    TheDoc
    Member

    Doesn’t $(this) reference $('.color')?

    Not really the way you’re thinking it does.

    In this case, $(this) refers to the element with a class of color that has been clicked, not all elements with the class of color like saying $('.color') means.

    #148974
    __
    Participant

    More specifically, this refers to the execution context you’re currently operating in (which in this case, as TheDoc points out, is the html element that was clicked on). Doing $(this) isn’t using this as a selector, it’s wrapping the element itself in a jQuery object so you can use jQuery methods on it.

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