How to use setAttribute() In Javascript
In this approach, we are using JavaScript’s setAttribute() method to dynamically add an ID to an HTML element. Select the element using getElementsByTagName() and then set its ID attribute with the value obtained from user input.
Syntax:
Object.setAttribute(attributename,value)
Example: The below example uses setAttribute() to add an ID to an element in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Example 1</title>
<style>
body {
text-align: center;
}
input {
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<h3>
Using setAttribute()
</h3>
<input type="text" placeholder="Enter ID">
<button onclick="addFn()">
Add ID
</button>
<script>
function addFn() {
const inputEle =
document.getElementsByTagName('input');
const temp = inputEle[0];
const val = temp.value;
temp.setAttribute('id', val);
alert('ID Added successfully!');
}
</script>
</body>
</html>
Output:
How to Add an ID to Element in JavaScript ?
In JavaScript, the ID is the unique identifier through which the elements can be identified and manipulated if required. We can add an ID to an element in JavaScript using various approaches that are explored in this article with practical demonstration.
Below are the possible approaches:
Table of Content
- Using setAttribute()
- Using Direct assignment to id property