I have a bunch of child elements that are uniquely identified within a parent div. I want to know if there's a way in jQuery (or javascript) to capture all of them? The number of children in the parent div is arbitrary, meaning it could be any number for each div. For example:
<div class="parent1">
<span class="child1">some text here</span>
<span class="child2">some other text</span>
...
<span class="child49">yet more text</span>
<span class="something_else">other text i don't want to select</span>
</div>
<div class="parent2">
<span class="child1">some text</span>
<span class="child2">some text</span>
...
<span class="child120">some text</span>
</div>
So considering the above example, how do I get ALL the children (.child1
through .child49
) within the class parent1
?
I know that doing the following will work in jQuery (using multiple selector):
$(".child1, .child2, ..., .child49").css("background","red");
But is there a better way? I won't always know how many children are in each parent.
EDIT: also, I might have other children in the parent with a different class name that I DO NOT want to select; I specifically want to select all the "child*" classes.
jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
$('.parent1 span[class^="child"]')
will select all the span
s that start with the class child
under the class .parent1
.
If you want all the span.childX
under all parentX
then use:
$('div[class^="parent"] span[class^="child"]')
This is using a CSS3 attribute selector
which jQuery have implemented (and extended in some cases). From the documentation:
E[foo^="bar"]
an E element whose "foo"
attribute value begins exactly with the string "bar"
These codes gets all child in div.parent1 and div.parent2
$('[class^="parent"] span').css({ });
$('[class^="parent"]').children().css({ });
Thess codes gets onli the children for parent 1
$('.parent1 span').css...
$('.parent1').children().css...
use .children
along with .filter
, if number of children are not certain then label all childs which you want to manipulate of parent1 as child1
$(".parent1").children().filter(".child1").css({color:'Red'});
here is the fiddle http://jsfiddle.net/8hUqV/1/
jquery children
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With