0

Is it possible to have two elements with the same data-attributes?

HTML

<div id="cerchi" class="container">

       <div class="row">

          <div class="col_6 clearleft">
             <div class="blu" data-link="nadir.php">
                <p>1</p>
             </div>
          </div>

          <div class="col_6 omega">
             <div class="arancione" data-link="sole.php">
                <p>2</p>
             </div>
          </div>

       </div>
</div>

JS

$("#cerchi .col_6 > div").click(function(){
   alert($("#cerchi .col_6 > div").data("link"));           
});

If yes, why if I click on the second "div" the alert gives the result "nadir.php"? instead of "sole.php"? do i something wrong?

Thanks in advance

4
  • 2
    Perhaps it is your JS code, which is not shown. Commented Feb 11, 2013 at 21:53
  • sorry i had forgotten it Commented Feb 11, 2013 at 21:55
  • 1
    Your JS has two results, you are only alerting the first. try a .each() loop and you'll see. Commented Feb 11, 2013 at 21:55
  • You have a logic issue with your selector. Think about what that selector does for a moment, forgetting the fact that it is inside a click event handler(because that doesn't matter). Commented Feb 11, 2013 at 21:55

1 Answer 1

3

Because it's looking for the first match. Change

$("#cerchi .col_6 > div").click(function(){
   alert($("#cerchi .col_6 > div").data("link"));           
});

to

$("#cerchi .col_6 > div").click(function(){
   alert($(this).data("link"));           
});
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thank you so much! especially for the speed at this time! I have yet to practice with jquery, i'm sorry :)
@Andrea - Everyone starts somewhere and this is one of those things that isn't necessarily obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.