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

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

3
  • 10
    Getting the ID of an element that has been selected via its ID? o.O May 23, 2019 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, 2020 at 3:50
  • Here ya go: gist.github.com/ykessler/52f8af9877a216a9169c9704b57ebf9e
    – Yarin
    Oct 23, 2022 at 15:42

20 Answers 20

2757

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.

19
  • 274
    It amazes me each time that jQuery does not have a shortcut for this like $('#test').id().
    – awe
    Apr 2, 2014 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, 2014 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 2, 2014 at 15:41
  • 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. Mar 28, 2015 at 22:24
  • 5
    Opps.. make that 1,122,603 times.. :P Aug 18, 2017 at 13:02
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})
3
  • 9
    BTW, I think retval.push($(this).attr('id')) can be written retval.push(this.id) Mar 31, 2014 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, 2014 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 8, 2015 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")
0
26

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

var myId = $("#test").prop("id");
2
  • 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. Jan 5, 2015 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.
    – ToniWidmo
    Dec 12, 2016 at 14:45
23
$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

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

Some checking code required of course, but easily implemented!

0
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/

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');
 });
1
  • It's disappointing the best answer is this far down the page. May 28, 2021 at 22:22
7

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

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

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 
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.

2
  • 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, 2022 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 at 5:22
6

    $("#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>

1
  • 1
    This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good 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 Aug 15, 2022 at 0:56
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

1
  • 1
    .. and also $('#test')[0].id which is the same as .get(0) Jul 13, 2010 at 17:24
3
$('tagname').attr('id');

Using above code you can get id.

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();
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!
2

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

0

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

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================
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.

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)
1
  • 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, 2019 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");

Not the answer you're looking for? Browse other questions tagged or ask your own question.