We can use JavaScript to set the id of an element by combining the querySelector() method along with the id property.
document.querySelector("#div1 p").id = "p1";
Let’s say I have the following HTML:
<div id="div1">
<p>This is a paragraph.</p>
</div>
If we want to set the id of the paragraph to “p1” we can use the id property to do this with the following JavaScript code.
document.querySelector("#div1 p").id = "p1";
The resulting HTML would be as follows:
<div id="div1">
<p id="p1">This is a paragraph.</p>
</div>
Using JavaScript to Set the Id of an Element With a Click
We can set the id of an HTML element using JavaScript very easily by combining the id property with an onclick event.
In this example, we will have a paragraph with no styles. We will then set the id of the paragraph so that it will have different styles. The HTML setup is pretty simple.
Here is the HTML code:
<style>#p1 { font-weight: bold; text-decoration:underline; }</style>
<div id="div1">
<p>This is the paragraph that we can set the id of.</p>
<div class="click-me" onclick="setId1()">Set id p1</div>
<div class="click-me" onclick="removeId1()">Remove id p1</div>
</div>
We can utilize both the id property and the querySelector() method to set the id of the paragraph to #p1. If the paragraph has id “p1”, then it will have an underline and bold styles.
Below are the two functions that will allow the user to be able to set or remove the id of the paragraph. We can remove an id from an element using the removeAttribute() method.
Here is the JavaScript code:
function setId1(){
document.querySelector("#div1 p").id = "p1";
};
function removeId1(){
document.getElementById("p1").removeAttribute("id");
};
The final code and output for this example of using JavaScript to set the id of a div with a click is below:
Code Output:
This is the paragraph that we can set the id of.
Full Code:
<style>#p1 { font-weight: bold; text-decoration:underline; }</style>
<div id="div1">
<p>This is the paragraph that we can set the id of.</p>
<div class="click-me" onclick="setId1()">Set id p1</div>
<div class="click-me" onclick="removeId1()">Remove id p1</div>
</div>
<script>
function setId1(){
document.querySelector("#div1 p").id = "p1";
};
function removeId1(){
document.getElementById("p1").removeAttribute("id");
};
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to set the id of an element.
Leave a Reply