JQuery Selector for multiple elements of one ancestor

空扰寡人 提交于 2019-12-12 03:36:50

问题


I have a DOM structure similar to this:

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

How can I select some of the descendants of an ancestor?

Something like:

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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/31355393/jquery-selector-for-multiple-elements-of-one-ancestor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!