To get an element by id using jQuery, the simplest way is using the jQuery id selector.

$("#id-of-element")

Let’s say I have the following HTML:

This is a paragraph.

To get the div element by id using jQuery, we just will use the jQuery id selector with the following Javascript code. This allows us to get a specific HTML element by the ID attribute.

$("#div")

If the element exists in the DOM, then $(“#div”) will return a jQuery object which we can operate on. If the element does not exist, $(“#div”) will be empty.

If the element exists, we can then do something like add a style to the element:

$("#div").css("text-align","center");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div").css("text-align","center");

Get Element By ID On Click Using jQuery

Many times when creating a web page and the user experience, we want to do things when a user interacts with another element on the web page.

We can get an element by ID after a click using jQuery very easily by combining the jQuery ID selector and text() methods with a click event.

Let’s say we have the following HTML code and we want to select the div and change the background color.

Click Me to Select Div and Change Background Color

We can utilize the jQuery click() method and the jQuery ID selector to get both the click event and to select the div.

Below is the Javascript code which will allow the us to get the div element by ID using jQuery:

$("#click-me").click(function(){
    $("#div").css("background-color","green");
}); 

The final code and output for this example of how to get an element by ID on click using jQuery and Javascript is below:

Code Output:

Click Me to Select Div and Change Background Color

Full Code:


Click Me to Select Div and Change Background Color

<script> $("#click-me").click(function(){ $("#div").css("background-color","green"); }); </script>

Hopefully this article has been useful for you to understand how to use jQuery to get an element by ID.

Categorized in:

jQuery,

Last Update: March 4, 2024