1667
<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

Why doesn't the above work, and how should I do this?

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
  • 10
    Getting the ID of an element that has been selected via its ID? o.O – Martin Schneider May 23 '19 at 12:17
  • 2
    Sample code. I'm working on an event trigger that uses "this" and I need to know what triggered the event, and independently track how many times each element is triggered. Building a sample with "this" will be far too large. – Nelson May 20 '20 at 03:50
  • Here ya go: https://gist.github.com/ykessler/52f8af9877a216a9169c9704b57ebf9e – Yarin Oct 23 '22 at 15:42

20 Answers20

2750

The jQuery way:

$('#test').attr('id')

In your example:

$(document).ready(function() {
  console.log($('#test').attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

Or through the DOM:

$('#test').get(0).id;

or even :

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is

$('#test').prop('id')

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

dota2pro
  • 7,220
  • 7
  • 44
  • 79
instanceof me
  • 38,520
  • 3
  • 31
  • 40
  • 274
    It amazes me each time that jQuery does not have a shortcut for this like `$('#test').id()`. – awe Apr 02 '14 at 16:33
  • 6
    It would be rarely useful because id's are typically hard-coded into the HTML and JS. When you write JS, you already know the ID of some element, so you write that ID to retrieve the element. You rarely need to get the ID of an element programmatically. – daniel1426 Apr 30 '14 at 18:07
  • 11
    Make that 164969 times. Plus now I'm here. I have code that initializes forms. A few of the forms have special requirements. I _could_ look for specific form elements to decide what to do, but I think identifying the form - thus the id of the form - is the most logical and surefire way. – Slashback Aug 02 '14 at 15:41
  • 1
    JSF, for example, generates IDs for elements (if not defined). – frIT Aug 11 '14 at 14:44
  • 1
    Backbone catches all form submissive events, they can be thrown by any element -- you won't know the .id(). – Evan Carroll Nov 26 '14 at 09:32
  • 2
    @daniel1426 I for example need it because i create a structure of nested divs dynamically from json data. it's very usefull then if you can just build things like $('.div-structure').on('click', function(){ doStuffWith(**$(this).attr('id')**); }); – philx_x Mar 05 '15 at 16:55
  • 60
    Why would I need to get an element's id? Because I have an event handler attached to a class of elements, and I need to know which particular element triggered the event. I hope I'm doing this right. – Buttle Butkus Mar 28 '15 at 22:24
  • Why `$('[id^="begin"]').attr("id")` returns concatenated ids? – zygimantus Dec 22 '15 at 09:41
  • I've created a request in GitHub .. maybe something will be done :) https://github.com/jquery/jquery/issues/3413 – Ricky Levi Nov 28 '16 at 09:25
  • @RickyLevi doubt it, the JQuery gods (snobs) do not see any value in the ID or Name values. Guess the thought is that the selector approach could return multiple possible elements and therefore, no easy way to extract the ID, or IDs. If it is an `array`, then return an `array` of IDs otherwise it is a singleton and return the `id`. – GoldBishop Feb 09 '17 at 17:26
  • @GoldBishop yep, they've closed it :D – Ricky Levi Feb 13 '17 at 10:37
  • 1
    @RickyLevi well i posted a simple solution, below: http://stackoverflow.com/a/42144268/659246. Wasn't that hard to develop for my low level of skill. – GoldBishop Feb 13 '17 at 15:18
  • https://api.jquery.com/id-selector/ `$('#test')[0].id;` or `$('#tes[0]').id;` or `$('#test').get(0).id;` – xgqfrms Feb 26 '17 at 12:30
  • I got the point, but the example is a bit confusing, you are using id to get id? Or am I missing something? – Haider Mar 25 '17 at 02:46
  • The fact that `$(this.hash)` exists is justification enough to have something like `$(this.id)`, or may be it's just wishful thinking. – Anjan Biswas Apr 03 '17 at 04:08
  • jQuery is mainy used for its $('#element_id') and $('class tag'). Therefore it should be at worse about 200 bytes long code, NOT 97000! – TomeeNS May 20 '17 at 10:53
  • 5
    Opps.. make that 1,122,603 times.. :P – BvuRVKyUVlViVIc7 Aug 18 '17 at 13:02
  • as of JAN2018, prop() is prefered to attr() – comte Jan 14 '18 at 18:02
  • @comte why is that? – Drumnbass Apr 09 '18 at 11:06
95

$('selector').attr('id') will return the id of the first matched element. Reference.

If your matched set contains more than one element, you can use the conventional .each iterator to return an array containing each of the ids:

var retval = []
$('selector').each(function(){
  retval.push($(this).attr('id'))
})
return retval

Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map shortcut.

return $('.selector').map(function(index,dom){return dom.id})
Steven
  • 17,796
  • 13
  • 66
  • 118
  • 9
    BTW, I think `retval.push($(this).attr('id'))` can be written `retval.push(this.id)` – Darren Cook Mar 31 '14 at 13:26
  • If you need an attribute of HMTL5 data-** then use something like this: `return $('.selector').map(function(i, dom){ return $(dom).attr('data-id'); })` – revoke Nov 21 '14 at 13:00
  • The .selector property was deprecated in jQuery 1.7 and is only maintained to the extent needed for supporting .live() in the jQuery Migrate plugin. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set. – Andrew Day Dec 08 '15 at 18:10
42

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")
Anurag
  • 140,337
  • 36
  • 221
  • 257
26

Above answers are great, but as jquery evolves.. so you can also do:

var myId = $("#test").prop("id");
Chris
  • 968
  • 16
  • 27
  • 4
    @cjbarth `attr()` was added in 1.0, and `prop()` was added in 1.6, so I'm assuming your comment was `prop()` is the new way. – Erik Philips Jan 05 '15 at 23:05
  • 6
    @ErikPhilips I believe, rather than old way and new way, it depends whether you are interested in the original output when the page loaded (`attr`) or that potentially modified by script (`prop`). If you aren't actually modifying the `id` attribute of any element using client side script, then `prop` and `attr` are identical. – AntonChanning Dec 12 '16 at 14:45
23
$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

Some checking code required of course, but easily implemented!

stat
  • 239
  • 2
  • 2
9

If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });
Jay Query
  • 99
  • 1
  • 1
9

.id is not a valid jquery function. You need to use the .attr() function to access attributes an element possesses. You can use .attr() to both change an attribute value by specifying two parameters, or get the value by specifying one.

http://api.jquery.com/attr/

Joey C.
  • 2,168
  • 2
  • 16
  • 14
7

$('#test').attr('id') In your example:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 
Kumar
  • 214
  • 2
  • 7
6

Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery

if (window.jQuery) {
    $.prototype.id = function () {
        if (this.length > 1) {
            var val = [];
            this.each(function (idx, el) {
                val.push($(el).id());
            });
            return val;
        } else {
            return this.attr('id');
        }
    }
}

It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.

GoldBishop
  • 2,820
  • 4
  • 47
  • 82
  • Yes and essentially what I ended up doing. I used "$.fn.id = function() { ... }", but the result seems identical to yours: jqelement.id() = "...". Is "prototype" preferred over "fn"? – horace Dec 19 '22 at 21:36
  • @horace it guess it depends on your preference....as well, framework changes over time, so prototype may be an antique usage compared to current usage. – GoldBishop Jan 14 '23 at 05:22
4

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

you need to use $('#test').attr('id'), which returns your required ID of the element

This can also be done as follows ,

$('#test').get(0).id which is equal to document.getElementById('test').id

4

    $("#button").click(function() {
      var clickID = $("#testDiv").attr("id");
      console.log(clickID)
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="testDiv"> When button will click you'll get this id value </div>
<button id="button"> Button </button>
Umair Hanif
  • 144
  • 1
  • 2
  • 1
    This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32478456) – Trenton McKinney Aug 15 '22 at 00:56
3
$('tagname').attr('id');

Using above code you can get id.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
JayminLimbachiya
  • 971
  • 1
  • 13
  • 19
3

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();
Tom
  • 74
  • 4
2

This is an old question, but as of 2015 this may actually work:

$('#test').id;

And you can also make assignments:

$('#test').id = "abc";

As long as you define the following JQuery plugin:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

Interestingly, if element is a DOM element, then:

element.id === $(element).id; // Is true!
Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133
2

Since the id is an attribute, you can get it by using the attr method.

Micah Switzer
  • 144
  • 1
  • 11
0

This can be element id , class , or automatically using even

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
Develop4Life
  • 7,581
  • 8
  • 58
  • 76
0

This will finally solve your problems:

lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.

here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
 alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
    {
      name: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){

    //parsing the data should come here:
    //var obj = jQuery.parseJSON(data);
    //$("#"+id).val(obj.name);
    //etc.

    if (id=="btnhlp-1")
       $("#"+id).attr("style","color:red");
    $("#"+id).val(data);
    });
});




});
</script>
</head>
<body>

<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input>

</body>
</html>

code was taken from w3schools and changed.

user3495363
  • 349
  • 2
  • 11
0
<html>
<head>
  <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
<?php
    // include Database connection file 
    include("db_connection.php");

    // Design initial table header 
    $data = '<table class="table table-bordered table-striped">
                        <tr>
                            <th>No.</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email Address</th>
                            <th>Update</th>
                            <th>Delete</th>
                        </tr>';
    $query = "SELECT * FROM users";
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
    // if query results contains rows then featch those rows 
    if(mysqli_num_rows($result) > 0)
    {
        $number = 1;
        while($row = mysqli_fetch_assoc($result))
        {
            $data .= '<tr>
                <td>'.$number.'</td>
                <td>'.$row['first_name'].'</td>
                <td>'.$row['last_name'].'</td>
                <td>'.$row['email'].'</td>
                    <td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
                </td>
            </tr>';
            $number++;
        }
    }

    else
    {
        // records now found 
        $data .= '<tr><td colspan="6">Records not found!</td></tr>';
    }

    $data .= '</table>';
    echo $data;
?>

<script type="text/javascript">

    function DeleteUser(id) {
    var conf = confirm("Are you sure, do you really want to delete User?");
    if (conf == true) {
        $.ajax({
                    url:'deleteUser.php',
                    method:'POST',
                    data:{
                        id:id
                    },
            success:function(data){
                      alert('delete successfully');
                   }




}
});

deleteUser.php

<?php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
    // include Database connection file
    include("db_connection.php");

    // get user id
    $user_id = $_POST['id'];

    // delete User
    $query = "DELETE FROM users WHERE id = '$user_id'";
    if (!$result = mysqli_query($con, $query)) {
        exit(mysqli_error($con));
    }
}
?>
0

it does not answer the OP, but may be interesting to others: you can access the .id field in this case:

$('#drop-insert').map((i, o) => o.id)
mariotomo
  • 9,438
  • 8
  • 47
  • 66
  • 5
    I'm grateful to downvoters when they explain what's wrong in my understanding. otherwise I find them as interesting as a mosquito. – mariotomo Oct 31 '19 at 23:00
-1

Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");

Camila S.
  • 9
  • 1