We can use jQuery to set the id of a div by using the jQuery attr() method.

$("#div1 p").attr("id","p1");

Let’s say I have the following HTML:

This is a paragraph.

If we want to add an id to the paragraph in the HTML above, we can target that paragraph and then use the attr() method.

$("#div1 p").attr("id","p1");

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("#div1 p").attr("id","p1");

Using jQuery to Set the Id of a Div With a Click

We can set the id of an HTML element using jQuery very easily by combining the attr() method with a click 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 jQuery click() method and the jQuery attr() method to set the id of the paragraph to #p1. If the paragraph has id “p1”, then it will have an underline and bold style.

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 removeAttr() method.

Here is the JavaScript code below:

$("#click-me1").click(function(){
  $("#div1 p").attr("id","p1");
}); 
$("#click-me2").click(function(){
  $("#p1").removeAttr("id");
}); 

The final code and output for this example of using jQuery 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.

Set id p1
Remove id p1

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 jQuery to set the id of a div.

Categorized in:

jQuery,

Last Update: February 26, 2024