📅  最后修改于: 2023-12-03 15:16:44.115000             🧑  作者: Mango
jQuery makes it very easy to select elements from the DOM. One common task is to select child elements of a parent container. In this tutorial, we'll look at how to use jQuery to select child elements.
Let's assume we have the following HTML structure:
<div id="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
Our parent container has three child elements with the class "child". We will use jQuery to select these child elements.
To select child elements with jQuery, we need to use the children()
method. This method selects all the direct children of the element we want.
Here's how we can use the children()
method to select the child elements of our parent container:
var children = $('#parent').children('.child');
In this code, we're using jQuery to select the #parent
element and then calling the children()
method to select all the elements with the class child
.
Once we've selected our child elements, we can iterate over them and perform some operation on each element. To do this, we can use the each()
method.
Here's an example of how to iterate over our child elements and perform a simple operation on each one:
$('#parent').children('.child').each(function() {
// Do something with each child element
// For example, set the background color to red
$(this).css('background-color', 'red');
});
In this code, we're selecting the child elements, then using the each()
method to loop through each one. Inside the each()
loop, we're using jQuery to set the background color of each element to red.
Selecting child elements with jQuery is a simple task that can be done using the children()
method. Once we have selected our child elements, we can iterate over them using the each()
method and perform some operation on each one.