开发者

javascript/jquery select all child elements inside a parent element

开发者 https://www.devze.com 2023-03-26 13:05 出处:网络
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

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 sele开发者_高级运维ctor):

$(".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.


$('.parent1 span[class^="child"]')

will select all the spans 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

0

精彩评论

暂无评论...
验证码 换一张
取 消