How to Get & Set the ID of an element with JavaScript and jQuery
In this tutorial, we will learn how to get and set the ID attribute of any HTML element using pure JavaScript and jQuery.
Get Element ID with JavaScript
To get the ID attribute of an element we can access the id
DOM property. Let's get all the inputs on a page, loop through them and get each of their ID's.
<input type="text" name="day" id="day">
<input type="text" name="week" id="week">
<input type="text" name="month" id="month">
var inputs = document.getElementsByTagName('input');
for (let i of inputs) {
console.log(i.id);
}
day
week
month
Set Element ID with JavaScript
To set the ID attribute of an element, assign a new value to the id
property using the assignment operator (=
).
<div id="wrapper"></div>
document.getElementById('wrapper').id = 'foo';
<div id="foo"></div>
Get Element ID with jQuery
To get the ID attribute of an element with jQuery use the built-in attr()
method.
<div id="wrapper"></div>
var id = $('#wrapper').attr('id');
console.log(id);
wrapper
Set Element ID with jQuery
To set a new ID value to an element using jQuery, pass the new value as the second argument of the attr()
method.
<div id="wrapper"></div>
$('#wrapper').attr('id', 'foo');
<div id="foo"></div>
Conclusion
You now know how to set and get the ID attribute of any element using pure JavaScript and with a jQuery abstraction layer.