Welcome to our comprehensive guide on the JQuery .each() method! This powerful tool is a must-know for every web developer, as it helps you iterate over collections efficiently. Let's dive in!
.each()? 📝The .each() method in JQuery allows you to loop through a collection (array, list, or even DOM elements) and perform an operation on each item. It's a versatile function that makes working with JavaScript collections a breeze!
.each()? 💡.each()? 🎯Let's say you have an array of names and want to log each name to the console.
// HTML
<ul id="names">
<li>John</li>
<li>Anna</li>
<li>Peter</li>
</ul>
// JavaScript
$(document).ready(function() {
var names = ['John', 'Anna', 'Peter'];
$('#names li').each(function(index, value) {
console.log(names[index]);
});
});In this example, we're using jQuery to select the <ul> with the id names, and then looping through each <li> using the .each() method. We're logging the corresponding name from our names array to the console.
Let's create a simple to-do list app where we can add, delete, and mark tasks as completed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>To-Do List</h1>
<ul id="tasks"></ul>
<input type="text" id="taskInput" placeholder="Add task">
<button id="addTask">Add Task</button>
<button id="clearCompleted">Clear Completed</button>
<script>
$(document).ready(function() {
var tasks = [];
// Adding a task
$('#addTask').click(function() {
var task = $('#taskInput').val();
if (task !== '') {
tasks.push({ text: task, completed: false });
addTaskToDOM(task);
$('#taskInput').val('');
}
});
// Iterating over tasks and adding them to the DOM
function addTaskToDOM(task) {
$('#tasks').append('<li><input type="checkbox" id="task' + tasks.length + '"><label for="task' + tasks.length + '">' + task + '</label></li>');
}
// Marking a task as completed
$('#tasks').on('change', 'input[type="checkbox"]', function() {
var taskIndex = $(this).parent().index();
tasks[taskIndex].completed = $(this).prop('checked');
});
// Removing a completed task
$('#clearCompleted').click(function() {
for (var i = tasks.length - 1; i >= 0; i--) {
if (tasks[i].completed) {
$(tasks[i].html).remove();
tasks.splice(i, 1);
}
}
});
});
</script>
</body>
</html>In this example, we're creating a to-do list app where we can add, delete, and mark tasks as completed. When adding a task, we're using .each() to add each new task to the DOM.
What is JQuery `.each()` method used for?
That's all for now! We hope this tutorial has helped you understand the JQuery .each() method better. Stay tuned for more tutorials on JQuery and other exciting topics! 🎯🚀