Monday, 9 April 2012

jquery for each loop to read elements

How to read elements by using for each loop in jquery ?

function(index, Element) -- A function to execute for each matched element.

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Example  1: Iterates through the array displaying each value text:

<script type="text/javascript">

var arrvar = [ "sample javascript code1", "sample javascript code2", "sample javascript code1", "sample javascript code1", "sample javascript code1" ];


    jQuery.each(arrvar, function() {
         alert(this);
      });

</script>

Example 2:Iterates over div elements /controls

      <div id="div1">jquery call 1</div>
      <div id="div2">javascript alert 1</div>
      <div id="div3">jquery call 2</div>
      <div id="div4">javascript alert 2</div>
      <div id="div5">jquery call 3</div>

<script type="text/javascript"> 

//$(document).click(function() { // onclick of body content call $(document).ready(function() {
 
      $("div").each(function () {
        alert($(this).text());
      });
    });

</script>

 

 

 

No comments:

Post a Comment