Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>each() & map()</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <ul id="list"><li>10</li><li>20</li><li>30</li></ul> <button id="sum">Sum with each()</button> <button id="double">Double with map()</button> <pre id="out"></pre> <script> $("#sum").click(function(){ var s = 0; $("#list li").each(function(){ s += parseInt($(this).text(),10); }); $("#out").text("Sum = " + s); }); $("#double").click(function(){ var nums = $("#list li").map(function(){ return parseInt($(this).text(),10)*2; }).get(); $("#out").text("Doubled = " + nums.join(", ")); }); </script> </body> </html>
Output