Dominic Sore
Dominic Sore

Reputation: 385

jQuery .each() not recognising all elements.

So I have my grid based layout:

<div id="gridrow" class="clear">
<div id="gridsection" class="float-left">
    <div id="gridwrap">
        <div id="gridimage" class="clear"></div>
        <div id="gridtitle" class="clear">Title</div>
        <div id="gridinfo" class="clear">Info</div>
    </div>
</div>
<div id="gridsection" class="float-right">
    <div id="gridwrap">
        <div id="gridimage" class="clear"></div>
        <div id="gridtitle" class="clear">Title</div>
        <div id="gridinfo" class="clear">Info</div>
    </div>
</div>
<div id="gridsection" class="gridmiddle">
    <div id="gridwrap">
        <div id="gridimage" class="clear"></div>
        <div id="gridtitle" class="clear">Title</div>
        <div id="gridinfo" class="clear">Info</div>
    </div>
</div>

I then have this jQuery script:

$("#gridtitle").each(function(index){
    $("#gridtitle:eq("+index+")").click(function (){
        $("#gridimage:eq("+index+"), #gridinfo:eq("+index+")").slideToggle();
    });
});

I thought this would work (made logical sense) however, only the first grid element will work, any tips?

For more information please feel free to ask,

Thanks.

Upvotes: 0

Views: 166

Answers (3)

Itamar
Itamar

Reputation: 534

ID's are unique , you can only use one for each object. You might use classed instead, and change the selectors :

$(".gridtitle").each(function(index){
    $(".gridtitle:eq("+index+")").click(function (){
        $(".gridimage:eq("+index+"),.gridinfo:eq("+index+")").slideToggle();
    });
});​

Upvotes: 1

jeff
jeff

Reputation: 8348

That's because gridtitle is an id. You should instead change it to be a class and select it like this:

$(".gridtitle").each(function() { ... });

Upvotes: 0

Uhehesh
Uhehesh

Reputation: 516

Different elements must have differend IDs.

If two or more elements have the same ID, only first is used.

Upvotes: 2

Related Questions