Answer»
- The each() method in jQuery allows us to loop through different datasets such as arrays or objects (even DOM objects).
- It can be used to loop through a number of DOM objects from the same selectors.
- For example, if you want to add a width=“600” to all the images in a page then we select all images and loop through each of them and add width = "600" to each tag. We can write the code as below:
$("img").each(function(im){ $(this).attr("width","600") });
- $ is a jQuery object definer. In the above syntax, “this” is a DOM object and we can apply jQuery functions to only jQuery objects which is why we convert the DOM object to jQuery object by wrapping it inside the $ definer.
- We can also use each() to loop through the arrays of data and get the index and the value of the position of data inside the array.
- For example,
var list = ["InterviewBit", "jQuery", "Questions"]; $.each(list, function(index, value){ console.log(index + " "+ value); })
0 InterviewBit 1 jQuery 2 Questions
- You can also use each() to loop through objects.
- For example:
var obj = {"name":"InterviewBit","type": "jQuery"}; $.each(obj, function(key,value){ console.log(key + " - " + value); })
name - InterviewBit type - jQuery
|