Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click(): get attribute from DIVs with the same class

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?

like image 611
user1237757 Avatar asked Mar 06 '26 01:03

user1237757


2 Answers

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.

like image 118
Felix Kling Avatar answered Mar 08 '26 14:03

Felix Kling


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

$('.myClass').click(function() {
    alert($(this).attr("iditem"));
})
like image 26
Willem Mulder Avatar answered Mar 08 '26 15:03

Willem Mulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!