Tags : JavaScript Intro



Traversing in Jquery

We will now learn how to navigate the through web elements with Jquery. We will be able to find a specific element so that we can interact with it.


Open up the console in Chrome, make sure you loaded Jquery (you won't be able to use it if you don't).

index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/example.css">
  </head>
  <body>
    <div class="container">
      <h2>These are types of Nuts:</h2>
      <ul class="nuts">
        <li>Almonds</li>
        <li>Cashews</li>
        <li>Hazelnuts</li>
      </ul> 
      <h2>These are types of Apples:</h2>
      <ul class="apples">
        <li>Fiji</li>
        <li>Granny</li>
      </ul>
    </div>  
    <script src="scripts/jquery-1.11.3.js"></script>
    <script src="scripts/myscript.js"></script>
  </body>  
</html>
// Commands used in the console

$("ul")

$("ul.nuts")

$("ul.apples")

$("ul.apples li")

$("ul.apples li:first")

$("ul.apples").find("li")

$("ul.apples").find("li").first()

$("ul.apples").find("li").last()

$("ul.apples").find("li").last().parent();

$("ul.apples").siblings();

Try the following:

  • Get the siblings of the almond list item.
  • Get the parent of the hazelnut list item.
  • Try to use the next() or prev() methods on an element. More info here Jquery Tree Traversal
  • Try to chain methods together for example $("ul.apples").find("li").last() is chaining two methods. See how far you can go..