jQuery id Selectors for a particular element
In general the jQuery id selector selects only the first matched element. What if we wish the id of a particular element , for example, we may wish to select a particular if of a paragraph element and not a header element. To do that we may use the selection as
$("p#id1")
Which will select the paragraph element with id = id1 and not, say, an h2 element with id = id1. Take a look at the following example, where we have assigned same id to h2 element and p element and only p element gets selected gets selected.
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.8.0.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p#id1").hide(); }); }); </script> </head> <body> <h2 id = "id1">Reference Designer jQuery Tutorial with id = id1</h2> <p>First Paragraph with no id or class</p> <p id="id1">Second Paragraph with id = id1</p> <p>Third Paragraph with no id or class </p> <button>Click me and only second para will vanish</button> </body> </html> |
You may like to try this example here.
Notice that the selector
$("p#id1")
selects only
<p id="id1">Second Paragraph with id = id1</p>
and not the
<h2 id = "id1">Reference Designer jQuery Tutorial with id = id1</h2>
Exercise
1. Make changes in the code so that, on clicking the button the header with id=id1 as well as the paragraph with id=id1 vanish.