Use the jQuery attr()
Method
You can simply use the jQuery attr()
method to get or set the ID attribute value of an element.
The following example will display the ID of the DIV element in an alert box on button click.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Get ID of an Element</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style>
div{
padding: 20px;
background: #abb1b8;
}
</style>
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
var elmId = $("#test").attr("id");
alert(elmId);
});
});
</script>
</head>
<body>
<div id="test">#text</div>
<br>
<button type="button" id="myBtn">Show Div ID</button>
</body>
</html>
You can also get the ID of multiple elements having same class through loop, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Get ID of Multiple Elements</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style>
div{
padding: 20px;
margin-bottom: 10px;
background: #abb1b8;
}
</style>
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
var idArr = [];
$(".box").each(function(){
idArr.push($(this).attr("id"));
});
// Join array elements and display in alert
alert(idArr.join(", "));
});
});
</script>
</head>
<body>
<div class="box" id="boxOne">#boxOne</div>
<div class="box" id="boxTwo">#boxTwo</div>
<div class="box" id="boxThree">#boxThree</div>
<button type="button" id="myBtn">Show ID List</button>
</body>
</html>