Reputation: 558
I'm trying to implement the jQuery toggle item in my Rails 3.2.1 app.
I would like the toggle to work for each individual <li>
item on the <ul>
, so I can target which element to hide/show individually. But for some reason, only the top element has the toggle effect; the rest are not responding.
Here's the jsFiddle.
Can anyone explain why this is happening?
Upvotes: 1
Views: 127
Reputation: 186
It’s because your div
s all have the same id
, which is invalid HTML. Since the DOM is only expecting there to be one element with any given ID, then when you write $("#trigger")
, it only selects the first one it finds. Change the ID to a class.
<div class="trigger"> ...
And change your ID selector to a class selector.
$('.trigger').click(/* ... */);
Upvotes: 2
Reputation: 18593
Why do the elements have the same id
s? An ID should be unique. If you want to select all the <li>
s, use a CSS selector like $(".toggle-li")
.
Upvotes: 0
Reputation: 717
Multiple elements with the same id is invalid HTML, and jQuery will only target the first that it finds with that id.
I updated your fiddle to use a class instead of ids
<div id="trigger" class="trigger">
Then:
$(".trigger").click(function (){
$(".menu-item", this).toggle();
});
to target the class and not the id.
Upvotes: 0
Reputation: 8457
$(".trigger").click('.menu-item', function () {
$(".menu-item", this).toggle();
});
Upvotes: 0
Reputation: 444
ID attributes must be unique on the page. Change all the id="trigger" to class="trigger" then try:
$(".trigger").click(function (){
$(this).find('.menu-item').toggle();
});
Upvotes: 0