I'm trying to assign a class to an element upon detecting that it has a data-voted
attribute of "true"
, but the simple addClass line is not working.
I was using $(this)
until I read jQuery's documentation for each()
, and then switched to the following:
windowReady = ->
jQuery ->
$voteLinks = $('.vote-button a')
$voteLinks.each (i, current) ->
if $(current).data('voted') == "true"
$(current).addClass('voted')
$(window).load(windowReady);
$(window).on('page:load', windowReady);
$(this)
windowReady = ->
jQuery ->
$voteLinks = $('.vote-button a')
$voteLinks.each ->
if $(this).data('voted') == "true"
$(this).addClass('voted')
$(window).load(windowReady);
$(window).on('page:load', windowReady);
But even that is still not assigning a class, even though I've confirmed that it does have the data-voted
attribute of "true"
CoffeesSript can be converted to Javascript at js2coffee.
Apparently, there is some flipflopping going on behind the scenes.
The coffeescript normally takes a
==
and turns it into===
. So according to the===
, it should check for type as well. So whendata-voted
is"true"
, you'd think you would have to compare it to"true"
. NOPE.Apparently, any data attributed that you reference or obtain via
.data()
,"true"
or"false"
gets turned back into booleantrue
/false
.Thus you have to leave the coffeescript as using
==
, which in javascript is actually===
, which checks for the type of variable (needs to be boolean, not a string).what implicit background craziness. Documentation, documentation, documentation. Lack of it, or not reading it wastes life. Thus documentation saves lives xp
As a complement to the answer by @gwho, this implicit type conversion is in fact a documented feature of JQuery:
As explained in the above quote, if you "don't like" implicit conversion, you might prefer using
attr()
(using the full attribute name) instead ofdata()
:And if you can live with that implicit conversion: