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

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,

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

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

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

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

Related: How to Get the Number from an Element’s ID using jQuery replace() Method Example

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.

Previous - Using jQuery mousemove() Method to Capture Mouse Pointer LocationNext - Export HTML Table to Excel using jQuery table2excel Plug-in



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!