aliyahmaliyah aliyahmaliyah -4 years ago 52
CSS Question

Store jquery in a variable

I've got an FAQ page I'm building. Next to the question, there is a plus sign to expand the content. On click, I've added the class active, but there are many questions, and I don't want to repeat the same jqeury snippet for each question. I've figured out how to find the parent ID but I'm having trouble storing it in an variable to reuse in the jquery script.

What I want to be able to do:

var element = $(this).parent().parent().attr('id')

$('.expand').click(function(){
$('element .expand').toggleClass('active')
})


Is there a way to do this? I get undefined when I do this:

$('.expand').click(function(){
console.log(element)
});

Answer Source

You can use the find() function to locate children of a selected element:

var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){ 
    $("#" + element).find('.expand').toggleClass('active')
});

However, looking at your code, it seems like you just want to toggle the "active" class of the clicked element. If that is the case, you can do this much more simply without a variable at all:

$('.expand').click(function(){ 
    $(this).toggleClass('active')
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download