How to Get the ID’s of Every DIV element using jQuery

← PrevNext →

I am sharing a simple tip here today on how to get the ID’s of every DIV element on a web page using jQuery. You can use jQuery attr() and prop() methods to retrieve element ids.

To retrieve ids of multiple <div> elements, you will have to iterate or loop through each element on your web page using jQuery .each() method.

Get Element IDs using jQuery attr() Method

The attr() method retrieves the attributes of an element. The id is one attributes. For example,

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
    <p>See the output in your browsers console window!</p>

    <div id="div1">
        Contents in DIV1
    </div>
    <div id="div2">
        Contents in DIV2
    </div>
</body>

<script>
    $(document).ready(function () {
        $('div').each(function () {
            var i = $(this).attr('id');
            console.log(i);
        });
    });
</script>
</html>
Try it

Loop through all <div> elements using .each() method and get ids using jQuery .attr() method.

Or...

You can have a parent and child <div>. For example,

<div id="divParent">
    Contents in Parent DIV

    <div id="divChild">
        Contents in Child DIV
    </div>
</div>
The Script
$('div').each(function () {
    var i = $(this).attr('id');
    console.log(i);
});

Note: If you know the id of the element, you can specify the element’s id as the selector, instead of div. For example,

var iD = $('#divChild').attr('id');
console.log(iD);

Get Element IDs using jQuery prop() Method

jQuery introduced the .prop() method in its version 1.6. This method retrieves property values of an element.

Simply replace the .attr with .prop in the above examples.

$('div').each(function () {
    var i = $(this).prop('id');
    console.log(i);
});

If it’s just about getting or retrieving the ID’s of elements, you can either use the .attr() method or the .prop() method. However, it is recommended to use the .prop() method, as it more convenient to deal with element properties.

← PreviousNext →