0

I'm trying to implement an accordion. I'm having a problem with comparing an element in the .each() loop.

I start by finding the .accordion who's .content I need to expand. This is the parent of the .accordion .title element that was click (line 6 below).

I then loop through each .accordion on the page. I try to detect which of those .accordion is the parent, to expand his .content. This isn't working.

// ACCORDION
var accordions = $('.accordion').toArray();

// Scroll down on click
$('.accordion .title').click(function() {
    var parent = $(this).parent();


    $(accordions).each(function() {

        // Show this accordion if it's the parent of the .title clicked
        // Problem is here ********
        if ( $(this) == parent )
            $(this).children('.content').slideDown();

        // Hide all accordions except this parent
        else {
            $(this).children('.content').slideUp();
        }

    });

});

My main question is a bit wider than this particular example:

How can I figure out if $(this) == some_var_pointing_to_an_element when looping through an array of elements like above?

EDIT: My accordion html if it's relevant:

<div class=".accordion">
    <div class=".title">Hello</div>
    <div class=".content">World</div>
</div>
Juicy
  • 11,840
  • 35
  • 123
  • 212
  • Use `var parent = this.parentNode;` and then `if (this == parent) { ... }`. – Ja͢ck Aug 04 '14 at 01:48
  • Though I don't recommend it in this situation, you can see [this question](http://stackoverflow.com/questions/2436966/how-would-you-compare-jquery-objects) on how to compare elements in jquery objects. – James Montagne Aug 04 '14 at 01:57

2 Answers2

3

There's no need to loop at all. Just do this:

// hide the others
$(accordions).not(parent).children(".content").slideUp();

// show this one
parent.children(".content").slideDown();
James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Up-voted, though I'd maybe suggest `slideToggle()` for the last line (if the OP wants to be able to close the accordion, for example). – David Thomas Aug 04 '14 at 01:52
2

Object comparison in JavaScript only works if both are the same instance (i.e. same memory location), but each time you use the $() constructor it will create a new instance.

That said, you can simplify the code somewhat by making jQuery do the looping work for you:

// ACCORDION
var $accordions = $('.accordion');

// Scroll down on click
$accordions.find('.title').click(function() {
    var $parent = $(this).parent();

    $accordions
      .not($parent) // all but this one
      .children('.content');
      .slideUp();

    $parent.children('.content').slideDown();
});
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309