1

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 ?

5 Answers 5

4

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'); 
});
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

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/

Comments

0

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>

Comments

0

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'); 
});

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.