jQuery id Selectors more details



In general the jQuery id selector selects only the first matched element. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element. As you may know a document with more than one element using the same ID is invalid.

You must note that it is not a good html coding habit to assign same ip to more than one html entity.

Take a look at the following example, where we have assigned same id to more than one element, only the first occurence of gets selected.


  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
  5. <script type="text/javascript">
  6. $(document).ready(function(){
  7. $("button").click(function(){
  8. $("#id1").hide();
  9. });
  10. });
  11. </script>
  12. </head>
  13.  
  14. <body>
  15. <h2>Reference Designer jQuery Tutorial</h2>
  16. <p>First Paragraph with no id or class</p>
  17. <p id="id1">Second Paragraph with id = id1</p>
  18. <p id="id1">Third Paragraph with id = id1 </p>
  19. <button>Click me and only 2nd paragraph will vanish</button>
  20. </body>
  21. </html>



You may like to try this example here.

Notice that the selector
 $("#id1") 

does not tell if it will apply to a paragraph or another element ( for example an h2 header). It will just match the first occurence of that id to whichever element it belongs to. In the next chapter we will see how to select an id of a particular element.

Take a look at the following example, where we have assigned same id to the <h2> element and the <p> element and the selection applies to the first occurence of the selection - in this case the <h2> element



  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
  5. <script type="text/javascript">
  6. $(document).ready(function(){
  7. $("button").click(function(){
  8. $("#id1").hide();
  9. });
  10. });
  11. </script>
  12. </head>
  13.  
  14. <body>
  15. <h2 id = "id1">Reference Designer jQuery Tutorial with id = id1</h2>
  16. <p>First Paragraph with no id or class</p>
  17. <p id="id1">Second Paragraph with id = id1</p>
  18. <p>Third Paragraph with no id or class </p>
  19. <button>Click me and only header will vanish</button>
  20. </body>
  21. </html>



You may like to try this example here.