To add an id to a HTML div using jQuery, the simplest way is to use the attr() method.
$("div").attr("id", "div1");
Let’s say I have the following HTML:
This is a paragraph.
If we want to add the id “div1” to the element with class “class1”, we can use the jQuery attr() method to do this with the following Javascript code.
$(".class1").attr("id", "div1");
The resulting HTML would be as follows:
This is a paragraph.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery(".class1").attr("id", "div1");
Adding an Id to an HTML Element Using jQuery With a Click
We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event.
Let’s say we have the following HTML code and we want to give the user the ability to add an id to the paragraph. The new id will underline the paragraph content.
Click me to add an id to the paragraph below
This is the paragraph we will add an id to.
We can utilize both the jQuery click() method and jQuery attr() method to add an id to the paragraph and make the contents underlined.
Below is the Javascript code which will allow the user to be able to add an id to the paragraph:
$("#click-me").click(function(){
$(".p").attr("id", "p-new");
});
The final code and output for this example of how to add an id using jQuery and Javascript is below:
Code Output:
Click me to add an id to the paragraph below
This is the paragraph we will add an id to.
Full Code:
Click me to add an id to the paragraph below
This is the paragraph we will add an id to.
<script>
$("#click-me").click(function(){
$(".p").attr("id", "p-new"); // this will add the id "p-new" to the paragraph with class "p"
});
</script>
Hopefully this article has been useful for you to understand how to add id to a div and HTML element using jQuery.