3

I have a problem with click event; here's the code:

jQuery:

$(document).ready(function() {
    $('.myClass').click(function() {
        alert($(.myClass).attr("iditem"));
    });
});

HTML:

<div class="myClass" iditem="1">
    1 
</div>
<div class="myClass" iditem="2">
    2
</div>

Two DIV with same class, but different values for the same attribute, when I click on a DIV, alert print always "1" (it seems ignoring the declaration of second DIV). Why .attr() doesn't take the right value for the second DIV?

1
  • missing quotes, else use a "this" Commented Feb 28, 2012 at 12:04

4 Answers 4

12

Assuming you have $('.myClass').attr("iditem"), this will always return the attribute of the first element in the set, as described in the documentation [docs] þ:

Get the value of an attribute for the first element in the set of matched elements.

So instead of selecting all elements with class myClass (that's what $('.myClass') does, no matter where/when it is called), you want to get a reference to the clicked element. Simply do:

$(this).attr('iditem');

this always refers to the element the event handler was bound to.

I suggest to use HTML5 data-* attributes instead of custom attributes, to have at least valid HTML5:

 <div class="myClass" data-item="1">

You can then use .data() [docs] to retrieve the value.


þ: You really should read jQuery's documentation. It provides many examples and a detailed description of how each method works. Make sure you also understand how selectors [docs] work.

Sign up to request clarification or add additional context in comments.

Comments

1

I assume you want to show the itemid of the item you click on? Then, this works:

$('.myClass').click(function() {
    alert($(this).attr("iditem"));
})

Comments

0

alert($(".myClass").attr("iditem"));

Comments

0

$(".myClass") returns all elements with the class myClass. I think you want something like this instead:

    $(document).ready(function()
    {
        $('.myClass').click(function() {
            alert($(this).attr("iditem"));
        });
    });

Comments

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.