jQuery: Iterate over each element of a selector
Tip by Stefan Trost | 2013-03-10 at 21:38
Sometimes, it is necessary to assign a value, an action, a CSS property or whatever to all elements of a jQuery selector. Today, I want to show you a way of how to do that.
So, let's have a look at the following code snippet.
$.each($(".a"), function() { $(this).val('abc'); });
We are using $.each for iterating. As a first parameter we are passing the jQuery selector that is $(".a") in the example, but you can also use any other selector you can imagine. As a second parameter, we are passing a function in which we can access the current element of the iteration loop with $(this).
In the example above, we are just changing the value of each element with the class "a" to "abc". Again, of course, you can use any other action you want to do within the function.
Alternative Syntax
The same can be done with the following syntax:
$(".a").each(function() { $(this).val('abc'); });
Also this iterates over all elements with the class "a".
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile
Related Topics
CSS: Include CSS Stylesheets in HTML
Tutorial | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
jQuery: Does an Element exist?
Tip | 1 Comment
HTML: Difference between ID and CLASS
Info | 0 Comments
jQuery: CSS Stylesheet Switcher
Tutorial | 1 Comment
Darken Background of a Website (Gray Out Effect)
Tutorial | 0 Comments
jQuery: Show and hide elements
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.