WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Get the ID of an Element using jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: 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.5.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.5.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>

You can also get the ID of individual element when using class selector based on index starting from 0, for example, to get the ID of first element in a set of matched elements you can use $(".box").get(0).id or $(".box")[0].id.

Similarly, to get the ID of last element you can use something like this, $(".box").get($(".box").length - 1).id or $(".box")[$(".box").length - 1].id, because jQuery selector returns a collection of matched elements not a single element.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties