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:
<div id="div">
<p>This is a paragraph.</p>
</div>
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.
<div id="div">
<p id="click-me">Click Me to Select Div and Change Background Color</p>
</div>
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:
<div class="html-code-output">
<div id="div">
<p id="click-me">Click Me to Select Div and Change Background Color</p>
</div>
</div>
<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.
Leave a Reply