jytoronto
jytoronto

Reputation: 558

jQuery toggle only working for the top element in the <ul>

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

Answers (5)

taldonn
taldonn

Reputation: 186

It’s because your divs 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(/* ... */);

jsFiddle

Upvotes: 2

NeoWang
NeoWang

Reputation: 18593

Why do the elements have the same ids? An ID should be unique. If you want to select all the <li>s, use a CSS selector like $(".toggle-li").

Upvotes: 0

AndrewK
AndrewK

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

DevlshOne
DevlshOne

Reputation: 8457

JSFIDDLE

$(".trigger").click('.menu-item', function () {
    $(".menu-item", this).toggle();
});

Upvotes: 0

mcbex
mcbex

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

Related Questions