Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to select child elements of parent?

Sorry if the title is not accurate - I couldn't figure out how to word it.

I have multiple widgets with the same class <div class="widget"></div> - each widget has a title, and content, structured like this:

<div class="widget">
    <div class="widget-title">Title</div>
    <div class="widget-content">Content Here</div>
</div>

The "widget-content" is hidden, and when you click on the widget-title, the content appears, and a class is applied to the widget-title, changing it to "widget-title open". This part works find, and the widget-content opens too.

The problem is, its opening the widget content on ALL widgets. It should only open the widget-content in the specific widget where the title was clicked, not ALL of them. I am not sure what the proper syntax is to use so it only opens the widget-content of the specific widget the user click the title on.

Here is the code I have so far:

$('.widget').find('.widget-title').click(function() {
  $('.widget-content').show('slow', function() {
    // Animation complete.
  });
  $('.widget').find('.widget-title').addClass("open");
});

Could someone please provide a working example? Thanks

like image 232
Zach Nicodemous Avatar asked Nov 29 '22 09:11

Zach Nicodemous


2 Answers

$('.widget .widget-title').click(function() {
    $(this)
        .addClass("open")
        .parent().find('.widget-content').show('slow', function() {
            // Animation complete.
        });
});
like image 144
simshaun Avatar answered Dec 05 '22 14:12

simshaun


I think you want this:

$('.widget').find('.widget-title').click(function() {
    $(this).parent().show('slow', function() {
        // Animation complete.
    }).addClass("open");
});

It opens the parent of the selected .widget-title element.

like image 23
Elliot Bonneville Avatar answered Dec 05 '22 12:12

Elliot Bonneville