jQuery Sibling Selector

jQuery sibling selector $("A + B") is used to select and element B that just comess after A. We just add a plus sign between two selectors (which can be any type of selector: IDs, classes, or elements). The selector on the right is the one to select, but only if it comes directly after the selector on the left

Take a look at the following example, where we have two tables and three links in the html.

  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. $("table+a").hide();
  9. });
  10. });
  11. </script>
  12. </head>
  14. <body>
  15. <h2>Reference Designer jQuery Tutorial</h2>
  17. <p> Table #1 </p>
  18. <table border = 1">
  19. <tr> <td> 1</td>
  20. <td> 2</td>
  21. </tr>
  22. <tr> <td> 3</td>
  23. <td> 4</td>
  24. </tr>
  25. </table>
  27. <a href ="http://referencedesigner.com"> Reference Designer Link #1 </a>
  29. <p> Table #2 </p>
  30. <table border = 1">
  31. <tr> <td> 1</td>
  32. <td> 2</td>
  33. </tr>
  34. <tr> <td> 3</td>
  35. <td> 4</td>
  36. </tr>
  37. </table>
  38. <a href ="http://referencedesigner.com"> Reference Designer Link #2 </a>
  39. <p> some other text </p>
  40. <a href ="http://referencedesigner.com"> Reference Designer Link #3 </a>
  41. <br />
  42. <button>Click me and Reference Designer Link #1 and #2 will vanish</button>
  44. </body>
  45. </html>

You may like to try this example here.

Notice that the selector


It select the the element a which is sibling of the table. So how it is different from selecting just the

The $("a") will selet all occurrences of the a element and will make all the links vanish. Try to make this change in the online program above and see the result.

Exercise 1

Write the code that will vanish the two tables in the above example on clicking the Button. Check your answer here.

Exercise 2

In the above example, look at the line 8


If this is replaced by


what will happen if the button in clicked. Make a guess and check it here.