To understand ID Selectors, let us take the below example, where we have three <p> tags.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <p id = "para1"> First Paragraph </p> <p id = "para2"> Second Paragraph </p> <p id = "para3"> Third Paragraph </p> </body> </html>
Now since, in the above code, there are three <p> tags,
<p id = "para1"> First Paragraph </p> <p id = "para2"> Second Paragraph </p> <p id = "para3"> Third Paragraph </p>
We have used the CSS ID attributes for each <p> tags. So that we can differentiate between the three <p> tags.
Now, let us say, we want to change the contents of the first <p> tag,
<p id = "para1"> First Paragraph </p>
From First Paragraph to My New First Paragraph using JQuery.
Now since, there are three <p> tags, we need to specify the ID Selectors to make use of the CSS ID name i.e. para1.
<p id = "para1"> First Paragraph </p>
So, let us rewrite the above code using ID Selectors of JQuery.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <p id = "para1"> First Paragraph </p> <p id = "para2"> Second Paragraph </p> <p id = "para3"> Third Paragraph </p> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('#para1').text("My New First Paragraph"); </script> </body> </html>
So, if you see the above output. We can see that the content of the first <p> tag,
<p id = "para1"> First Paragraph </p>
Got changed to My New First Paragraph.
And this happened with the one liner code of JQuery.
<script> $('#para1').text("My New First Paragraph"); </script>
In the JQuery code we have located the <p> element and specified the ID name followed by .' i.e. #para1.
Just remember, in the ID selector, the ID name should start with a hash # i.e. #para1.
$('#para1').text("My New First Paragraph");
So, when JQuery finds that a selector that starts with a hash # (i.e. #para1), it assumes that we ar searching for a CSS ID.
And finds that there are three elements with ID attribute.
<p id = "para1"> First Paragraph </p> <p id = "para2"> Second Paragraph </p> <p id = "para3"> Third Paragraph </p>
And the first attribute,
<p id = "para1"> First Paragraph </p>
Matches with the ID name para1. And changes its content with My New First Paragraph.