Reputation: 53
I'm looking for a way to select the first child element of multiple parent divs, of which the parent divs have the same class. This is my HTML:
<div class="wrapper">
<p>Select this paragraph</p>
</div>
<div class="wrapper">
<img src="https://picsum.photos/200/300" title="Select this image">
<p>Don't select this</p>
</div>
<div class="wrapper">
<p>Select this paragraph</p>
<p>Don't select this paragraph</p>
</div>
Please see my full CodePen Here.
I'm trying to select the first child element of each div with the class wrapper
and apply the same class to all of these child elements. I was looking at something in the lines of this:
$('.wrapper').children(":first").addClass("noMargin");
The problem with this is that it only selects the child element of the first parent div, but it doesn't select the img
and the first p
of the third wrapper. I figured you need some kind of array for this and apply a class to all of them, but how can I achieve this (with preferably jQuery)?
Upvotes: 2
Views: 1285
Reputation: 5019
While I completely understand that the OP wanted a solution using jQuery, I'll post a native JavaScript solution here.
Select all elements with a specific class then loop through each element and get the first child. If a first child exists, do anything you want, in this case, add a specific class.
document.addEventListener("DOMContentLoaded", function () {
var wrappers = document.getElementsByClassName("wrapper");
for (var i = 0; i < wrappers.length; i++) {
var firstChild = wrappers[i].children[0];
if (firstChild) {
firstChild.classList.add("hidden");
}
}
});
.hidden {
display: none;
}
<div class="wrapper">
<p>Select this paragraph</p>
</div>
<div class="wrapper">
<img src="https://picsum.photos/300" title="Select this image">
<p>Don't select this</p>
</div>
<div class="wrapper">
<p>Select this paragraph</p>
<p>Don't select this paragraph</p>
</div>
Upvotes: 0
Reputation: 2348
you can use following sample it is working fine
$('.wrapper :nth-child(1)').addClass("noMargin");
or another syntax
$('.wrapper :first-child').addClass('noMargin');
Upvotes: 2
Reputation: 1377
You're close, what you need is to go through the elements that have the .wrapper
class and append the noMargin
class to their first children i.e
$('.wrapper').each(function() {
$(this).children(":first").addClass("noMargin");
});
Upvotes: 4