-->

22 April 2021

jQuery each function

  Asp.Net CS By Example       22 April 2021
jQuery each function

 In this post, we are learning about jQuery each() function. When we create a set of elements with the jQuery $() function and then apply a function such as css() to the set, jQuery applies the css() function to all members of the set automatically.

 However, sometimes we may want to apply a custom function one that we write ourself to the members of a set. For example, we may want to add a custom title attribute to all <img> elements in a set. We can start with this code, which lets we loop all <img> elements in the page.


 $("img").each(function(m){ 
   ...
 }); 

 In the body of the function, we can refer to each <img> element by index number, which is passed to we as the m parameter here. We can refer to the current element in each iteration with this keyword, so to give each <img> element an title element "Image 1", "Image2", and so on, we would use this code


 $("img").each(function(m){    
  this.alt="Image " + (m + 1);
 }); 

 Below code example puts for see above jQuery each() function working.

jqscript.html
<html>
<head>
    <title>
        Adding a title attribute
    </title>
    <script src="jquery-latest.js"></script>
    <script type="text/javascript">
        function AddTitle() {
            $("img").each(function(m){
                this.title= "Image " + (m + 1);
            });
        }
    </script>
</head>
<body>
    <h1>Adding a title attribute</h1>
    <img src="../../img/jquery-logo.png"  />
    <img src="../../img/jquery-logo.png"  />
    <br>
    <form>
        <input type="button"
               value="Add title attributes"
               onclick="AddTitle()"
        </input>
    </form>
</body>
</html>


Output:

logoblog

Thanks for reading jQuery each function

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.