Reputation: 12510
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>
Upvotes: 0
Views: 70
Reputation: 173542
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();
});
Upvotes: 2
Reputation: 78630
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();
Upvotes: 3