Get ID of an element with JavaScript/jQuery
This post will discuss how to get the ID of an element in JavaScript and jQuery.
The idea is to use the .attr() or .prop() method to get the id attribute value for the first matched element.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { alert($("input[type=text]").prop("id")); }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Get ID</button> |
Alternatively, you can just access the underlying HTMLInputElement and get its id property:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { alert($("input[type=text]")[0].id); }); }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Get ID</button> |
In plain JavaScript, you can do like:
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { alert(document.getElementsByTagName('input')[0].id); } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Get ID</button> |
That’s all about getting the ID of an element in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)