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:
This is a paragraph.
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:
This is a paragraph.
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:
This is the paragraph that we can set the id of.
Set id p1
Remove id p1
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:
This is the paragraph that we can set the id of.
Set id p1
Remove id p1
Hopefully this article has been useful for you to understand how to use JavaScript to set the id of an element.