user3750366 user3750366 - 3 months ago 12
jQuery Question

How to get value of id in an element

tried getting value of attributes. I can get values of other attributes but not the id. Here is my jquery code. While i can get the value of class, the value of id is either undefined or null.

$(".someClass").click(function(){
var id = $(this).attr("id");
var class = this.className;

alert(title);
alert(class);
});


Thanks

Answer

Your faults:

1- class is a reserved word. use another word.

2- You are not alerting the id

$(".someClass").click(function(){
    var myId = $(this).attr("id");
    var myClass = this.className;

    alert(myId);
    alert(myClass);       
});

Let's have a sample:

$(document).ready(function(){
$(".someClass").click(function(){
    var myId = $(this).attr("id");
    var myClass = this.className;

    alert(myId);
    alert(myClass);       
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="someClass" id='someId'>Click Me</div>

Comments