Javascript 有没有比调用parent().parent()更好的方法遍历dom?

Javascript 有没有比调用parent().parent()更好的方法遍历dom?,javascript,jquery,Javascript,Jquery,我把它作为我更大的代码的一部分,它看起来既丑陋又不切实际 if (!$(this).closest( "li" ).parent().parent().hasClass('mod-left') ) { $(this).closest( "li" ).parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true); $(this).closest( "li" ).parent

我把它作为我更大的代码的一部分,它看起来既丑陋又不切实际

if (!$(this).closest( "li" ).parent().parent().hasClass('mod-left') ) {
     $(this).closest( "li" ).parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
     $(this).closest( "li" ).parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
     $(this).closest( "li" ).parent().parent().parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
     $(this).closest( "li" ).parent().parent().parent().parent().parent().parent().parent().parent().find('.checkbox').first().find('.wf-check').prop('checked', true);
}
有更好的方法吗?

您可以使用

$(this).parents('selector')

如果您在dom树中有一个以上的类或id,您可以参考。

希望这对您有所帮助

$(this).parents('.class-of-any-parent').append('this is working');
有关更多详细信息,请访问jquery父级文档()


//这将在所选父对象中搜索复选框id并使其处于选中状态

在操作DOM时,决不应依赖HTML的结构和继承权。在前端工作中,您可以认为HTML是您的结构/布局层,CSS是您的表示/样式层,JS是您的逻辑。每个都应该是独立的

使用
$(this.parent().parent()时移动元素会破坏代码

我猜您在这里要做的是在每个父级中的第一个容器中用class
.wf check
.checkbox
类选中复选框

如果是这样的话,你可以考虑这样做:

$('.checkbox:first-child .wf-check', '.container').prop('checked', true);
您只需将上面的
.container
替换为包含所有复选框的最上层父类


这里是一个工作的

使用最接近的
li
,而不是最接近的
li
。您想做什么?很可能是的,但我们需要看到标记和类似
.find('.checkbox').first().find('.wf check')
可以清理到
.find('.checkbox:first.wf check'))
什么都说。。。只要找到正确的,或者向我们详细解释您在代码方面的具体问题。您可以这样做。
$(这个)。家长(“选择器”)
我真的怀疑这是否有帮助。从问题中的示例判断,
.wf check
不是此的祖先。如果是,就没有理由在链中的某个位置使用
.find('.wf check')
。但无论如何,我们只能确定是否看到HTML。不过最好使用
。最接近的
。或者与特定的选择器共享我可以给你代码的HTML。或者我没有问这个问题。
$('.checkbox:first-child .wf-check', '.container').prop('checked', true);