JQuery - How to select parent child elements?

Sorry if the title is not accurate - I could not figure out how to write it.

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

<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 the class is applied to the widget type, changing it to "widget-view-open". This part works, and the widget contents also open.

The problem is that it opens the contents of the widget to ALL widgets. It should only open the widget content in the specific widget where the title was clicked, and not ALL of them. I'm not sure I should use the correct syntax, so it only opens the widget content of a particular widget that the user clicks on the title.

Here is the code that I still have:

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

Can someone provide a working example? Thanks

+3
source share
7 answers
$('.widget .widget-title').click(function() {
    $(this)
        .addClass("open")
        .parent().find('.widget-content').show('slow', function() {
            // Animation complete.
        });
});
+15
source

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 item .widget-title.

+2
source

:

$('.widget-title').click(function() {
  $(this).parent('.widget').children('.widget-content').show('slow', function() {
    $(this).addClass('open');
  });
});
+2

,   $ ('# parent > childNode'); http://api.jquery.com/child-selector/

+1
0
source
$('div.widget-title').click(function() {
 var el = $(this);
 el.addClass('open');siblings('div.widget-content').show('slow',function() {
     //animation complete
 });
});

You need to save the callback function in context using the 'this' keyword, which refers to the current DOM element. Otherwise, you will just grab all the DOM elements with the widget header class inside your callback.

0
source

If you select a class, jquery will select all members of this class. Is it possible to set an identifier or attribute for this particular widget or parent container?

0
source

All Articles