Javascript Add ID to Element
Adding an ID to an element makes it easier to access that element using javascript. IDs are unique so we can uniquely identify an element using its ID.
Here is how a simple HTML element looks like.
<div>Hello World</div>
NAnd this is how element with an ID looks like.
<div id="myDiv">Hello World</div>
Here, myDiv
is the ID of the element.
Now, let's see how to add an ID to an element using javascript.
1. Using setAttribute() method
The setAttribute()
method is used to set the value of an attribute of an element. It takes two parameters, the name of the attribute and the value of the attribute.
To set the ID of an element, we will pass id
as the first parameter and the ID value as the second parameter.
let div = document.createElement('div');
div.setAttribute('id', 'myDiv');
Here, we have created a div element and set its ID to myDiv
.
Now, let's see how to add an ID to an existing element.
let div = document.querySelector('div');
// using setAttribute() method
div.setAttribute('id', 'myDiv');
Here, we have selected the first div element and set its ID to myDiv
.
Here is a working example of adding an ID to an element using javascript.
Example
<div>Hello World</div>
<button onclick="addId()">Add ID</button>
<script>
function addId() {
let div = document.querySelector('div');
// using setAttribute() method
div.setAttribute('id', 'myDiv');
}
</script>
Output:
2. Using id property
Every HTML element has a built-in id
property that represents its ID attribute. You can directly access this property and assign it the desired ID value.
// Select the element you want to add an ID to
let element = document.querySelector('.my-element');
// Add an ID to the element
element.id = 'my-id';
In the above code snippet, we used the querySelector() method to select the element with the class .my-element. Then, we assigned the ID my-id to the id property of the element.
Let's see a working example of adding an ID to an element using the id property.
Example
<p class="my-element">Hello World</p>
<button onclick="addId()">Add ID</button>
<script>
function addId() {
let element = document.querySelector('.my-element');
// Add an ID to the element
element.id = 'my-id';
}
</script>
Output:
Conclusion
Adding an ID to an HTML element dynamically using JavaScript allows you to target and manipulate the element with ease.
Now that you know how to add an ID to an element using JavaScript, you can make your code more dynamic and interactive.