.each() — loop over elements
$('.price').each(function (index) {
console.log(index, $(this).text());
});
Inside, $(this) is the current element. return false; stops the loop.
$.each() — loop over arrays and objects
$.each(['HTML', 'CSS'], function (i, value) { ... });
$.each({ name: 'Asha', age: 20 }, function (key, value) { ... });
.data() and data-* attributes
HTML can carry extra information:
<button data-id="42" data-price="499">Buy</button>
Read it: $(this).data('price') → 499 (jQuery converts numbers automatically).
Store data on an element without changing the HTML: $('#box').data('clicks', 5);
data-* attributes are the clean way to pass IDs from your PHP/Blade code to jQuery.
Example
Example — Total with each() and data()
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<ul>
<li class="course" data-id="1" data-fee="999">HTML Course</li>
<li class="course" data-id="2" data-fee="1499">CSS Course</li>
<li class="course" data-id="3" data-fee="2499">jQuery Course</li>
</ul>
<button id="calc">Calculate total fee</button>
<pre id="out"></pre>
<script>
$(function () {
$('#calc').click(function () {
let total = 0;
let lines = [];
$('.course').each(function (i) {
const fee = $(this).data('fee');
total += fee;
lines.push((i + 1) + '. ' + $(this).text() + ' (id ' + $(this).data('id') + '): ₹' + fee);
});
lines.push('Total: ₹' + total.toLocaleString('en-IN'));
const skills = { level: 'Beginner', mode: 'Online' };
$.each(skills, function (key, value) { lines.push(key + ' → ' + value); });
$('#out').text(lines.join('\n'));
});
});
</script>