Question

I am trying to find out how to show/hide an element depending on the fact whether the element ".question a" has the class "checked" or not. But it isn't working. Anybody knows why ;( ?

$().ready(function() {

    var myLink = ".question a";
    if (myLink.hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});
Was it helpful?

Solution

Try like

$(document).ready(function() {
    var myLink = $(".question a");
    if (myLink.hasClass('checked')) { //You can also use $(this).hasClass
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   
});

If you want to change the status of link then call the same while your event triggered like

$(myLink).on('click',function(){
    if ($(this).hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }
});

OTHER TIPS

Try

$(function() {

    var myLink = $(".question a"); // need to use jQuery selector here
    if (myLink.hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});

Repalce

var myLink = ".question a";

With

var myLink = $(".question a");

add $ before myLink

$(document).ready(function() {

    var myLink = ".question a";
    if ($(myLink).hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top