Skip to content Skip to sidebar Skip to footer

JQuery Selector For Multiple Elements Of One Ancestor

I have a DOM structure similar to this:

Solution 1:

If you replace your 'id's with classes (since ids should be unique), then,

<div id="ans1">
    <input class="in1" />
    <input class="in2" />
</div>
<div id="ans2">
    <input class="in1" />
    <input class="in2" />
</div>

Then, to select all the descendants of id=ans1 having class="in1", you go like,

$('#ans1 .in1')

This will return an array of all the .in1 class elements inside id=ans1 element


Solution 2:

You can use the children function

$("#ans1").children("#in1, #in2")

You should use unique ids thought the DOM, use classes to specify elements that are the same in nature.

change your children to have same class of in1

$("#ans1 > .in1")

Will select all direct descendants of ans1 with class of in1.


Post a Comment for "JQuery Selector For Multiple Elements Of One Ancestor"