jQuery

[jQuery] jQuery/Method/.each() - Method that causes a function to run on each of the selected elements

OOQ 2022. 9. 9. 09:57
728x90
SMALL

#jQuery

#each()

.each()

.each() will repeat the function for each of the selected elements if there are multiple.

grammar

.each( function )

To break out of a repeat operation when certain conditions are met

return false

Use the.

example 1

Add a different class to each p element.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      .s1 {color: red;}
      .s2 {color: blue;}
      .s3 {color: green;}
      .s4 {color: brown;}
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        var i=1
        $( 'p' ).each( function() {
          $( this ).addClass( 's' + i );
          i = i + 1;
        } );
      } );
    </script>
  </head>
  <body>
    <p>Lorem</p>
    <p>Ipsum</p>
    <p>Dolor</p>
    <p>Amet</p>
  </body>
</html>

example 2

Repeat the work only twice to exit.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      .s1 {color: red;}
      .s2 {color: blue;}
      .s3 {color: green;}
      .s4 {color: brown;}
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        var i=1
        $( 'p' ).each( function() {
          $( this ).addClass( 's' + i );
          i = i + 1;
          if ( i == 3 ) {
            return false;
          }
        } );
      } );
    </script>
  </head>
  <body>
    <p>Lorem</p>
    <p>Ipsum</p>
    <p>Dolor</p>
    <p>Amet</p>
  </body>
</html>

 

728x90
LIST