We already discussed a little bit about jQuery id selector when we discussed the jQuery Selectors in detail. In this guide, we will focus only on jQuery element id selector and take few examples to understand the usage of this selector.
jQuery id Selector Syntax
$ sign followed by parenthesis and the id is mentioned inside the parenthesis prefixed with # sign.
$("#myid")
This will select the element that has the id equals to the myid
.
jQuery id Selector Example
In the following example we are selecting the element with the id value equals to "gid"
and then we are changing the background colour of that selected element to green when the Click Me! button is clicked.
Here we have a paragraph with the id value as "gid"
so the background colour of this para is changed to green when the button is clicked.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#gid").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery #id selector example</h2> <div> <p id="gid">This jQuery #id selector example is published on beginnersbook.com</p> <p>This is another paragraph. It contains some plain text</p> </div> <button>Click Me!</button> </body> </html>
Output: The following two screenshots show the output screen before and after the button is clicked.
Before the button click event:
After the button click event:
Leave a Reply