Tom
Tom

Reputation: 520

Selecting ID of a element in Jquery

I have following HTML code snippet.

<li my-id="10" class="my-class">test-1</li>
<li my-id="15" class="my-class">test-2</li>
<li my-id="20" class="my-class">test-3</li>

Can anybody help me how to get the id of the above one html element when a click event is occur. When explaining more, I have following code in jquery. When a user clicks on any of the above element I need to extract the id corresponds to same element. I use following code in jQuery.

$('.my-class').on('click', function(e) {
var ids = e.targetElement.attr('my-id'); 
});

But the above code snippet is not working. Can anybody suggest better method to do this ?

Upvotes: 1

Views: 72

Answers (5)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

Try, use atributes 'id' in your list

<li id="10" class="my-class">test-1</li>
<li id="15" class="my-class">test-2</li>
<li id="20" class="my-class">test-3</li>

And in javascript, this.id

$('.my-class').on('click', function(e) {
 var ids = this.id; 
 alert(ids);
});

And include jquery. Eg: https://jsfiddle.net/Cuchu/7h1ecsm7/

Upvotes: 0

Sarantis Tofas
Sarantis Tofas

Reputation: 5167

Just wrap this with jQuery then use the attr method to get the attribute you need:

$('.my-class').click(function() {
  var ids = $(this).attr('my-id'); 
});

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

attr() is a jQuery method so you should call it on jQuery object $(this) :

var ids = $(this).attr('my-id'); 

if you want javascript alternative you could use getAttribute :

var ids = e.target.getAttribute('my-id'); 

Hope this helps.


$('.my-class').on('click', function(e) {
    alert(e.target.getAttribute('my-id')+' ---- '+ $(this).attr('my-id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li my-id="10" class="my-class">test-1</li>
<li my-id="15" class="my-class">test-2</li>
<li my-id="20" class="my-class">test-3</li>

Upvotes: 0

Hakan Kose
Hakan Kose

Reputation: 1656

You need to use e.currentTarget as a selector like this.

$('.my-class').on('click', function(e) {
 var ids = $(e.currentTarget).attr("my-id");  
 alert(ids)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li my-id="10" class="my-class">test-1</li>
<li my-id="15" class="my-class">test-2</li>
<li my-id="20" class="my-class">test-3</li>

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Try to invoke .attr() over $(this). since .attr() will not be available in the prototype of a node object,

$('.my-class').on('click', function(e) {
 var ids = $(this).attr('my-id'); 
});

Upvotes: 4

Related Questions