[英]jQuery find child based on class selector matching parents
I am trying to find the descendants of a particular node using the jquery .find()
method. 我试图使用jquery
.find()
方法找到特定节点的后代。 I have noticed that .find()
doesnt match elements based on properties of parents above the current node in the tree. 我注意到
.find()
根据树中当前节点上方父项的属性不匹配元素。 The first find returns 0 elements, but the second find returns the element I was searching for. 第一个find返回0个元素,但第二个find返回我正在搜索的元素。 My question is, is this a limitation of the selector pattern allowed for the find method and is find the only jquery function that has this limitation?
我的问题是,这是否是find方法允许的选择器模式的限制,并且找到唯一具有此限制的jquery函数? I would have expected both of these to return the same element.
我希望这两个都返回相同的元素。 Also, is there another jquery method that would more succinctly accomplish the same thing as second one.
另外,是否有另一种jquery方法可以更简洁地完成与第二种方法相同的操作。 This is a simplified example of what I'm trying to do and I cannot remove the
.find('.input-group')
as this is an input into my function. 这是我正在尝试做的简化示例,我无法删除
.find('.input-group')
因为这是我的函数的输入。
$(document).find('.input-group').find('.form-group .form-control') $(document).find('.input-group').find('.form-control').filter('.form-group .form-control')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" aria-label="CVV Disabled" value=""> </span> <input id="vtCvv" name="vtCvv" type="password" class="form-control" required="true" data-bv-field="vtCvv"> </div> </div> </body> </html>
.find() looks for a descendant of an element. .find()查找元素的后代。 You're trying to find a parent and then a descendant.
你试图找到一个父母,然后是一个后代。
You could find .input-group
, then traverse backwards through the DOM to the "closest" .form-group
using .closest() and then you could navigate down to .form-control
like so: 您可以找到
.input-group
,然后使用.closest()向后遍历DOM到“最近的” .form-group
,然后您可以向下导航到.form-control
如下所示:
$(document).find('.input-group').closest('.form-group').find(".form-control")
or you could use .parent() to backtrack to .form-group
like so: 或者您可以使用.parent()回溯到
.form-group
如下所示:
$(document).find('.input-group').parent().find(".form-control")
I prefer .closest()
because if another element were to be added between .input-group
and form-group
the parent would be different, but .closest
would still work. 我更喜欢
.closest()
因为如果要在.input-group
和form-group
之间添加另一个元素,那么父元素会有所不同,但是.closest
仍然可以工作。
$('.form-group .input-group').find('.form-control');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.