jQuery select by ID allows you to find a specific HTML element with the value of its attribute – “id”. You can select and do the intended action on an element by making its id unique.
jQuery select by ID
Here is the general syntax for using the jQuery select by id:
$(“# ID”)
ID could be any value provided in the id attributes of the HTML element. You should use # followed by its ID in the selector.
For example, if there is a HTML element in the document like <div id=”text”> some text </div>, $(“#text”) will select the div with id equal to ‘text’ and do the intended action on it.
The main importance of this jquery selector is we will get separate control over each element by its unique id and the manipulations will affect only that element.
jQuery Select by ID Example
This example demonstrates the use of jQuery select by id and changing the CSS style of the selected element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<html> <head> <title>jQuery select by ID</title> <style> div { width: 80px; height: 80px; float: left; padding: 10px; margin: 10px; background-color: #eee; } </style> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <div id="div1"><p>id="div1"</p></div> <div id="div2"><p>id="div2"</p></div> <script> $( "#div1" ).css( "border", "5px solid green" ); </script> </body> </html> |
In this example you can see that <div> element with id=’div1′ is selected for manipulation.
Above HTML produces output as shown in below image.
jQuery select by id summary
Every HTML element can have unique id attribute. Therefore, it’s easy to get control over the element using the jQuery select by ID.
We can use this selector whenever we want to access a specific element to execute some task. Using this selector in combination could enhance the flexibility as well.