For Looping jQuery Elements

When you get a jQuery object back from a selector, you general loop through all of the elements it contains using .each(). However I wanted to use a For Loop because I wanted to access a bunch of elements at once. I am scrapping a table and I might want to access multiple elements to pull data from.

Figuring out how to do this was a little tricky. Luckily it is very easy to do:

<body>
  <div></div>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
<script>

    $(“body”).find(“div”).eq(2).addClass(“blue”);
</script>

 

Simply use .eq(index) to access a particular element in the jQuery object.

Leave a Reply

Your email address will not be published. Required fields are marked *