如何在元素父级兄弟选择器上运行.click? [英] how to run a .click on elems parent sibling selector?

查看:103
本文介绍了如何在元素父级兄弟选择器上运行.click?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我最近的尝试:

var aSl = document.querySelector('input[id^="blahblah"]');
aSl.closest("span.k-icon.k-i-expand").click();

返回:

myjs.js:181未捕获的TypeError:无法读取null的属性最接近"

我也尝试使用parent.sibling代替上面的.closest-返回'... parent不是函数'错误.

I have also tried parent.sibling in place of .closest above - that returned '...parent is not a function' error.

以下是我的标记:

<span class="k-icon k-i-expand">::before</span> <--- this is what I'm trying to run .click() on
<span class="k-checkbox-wrapper">
   <input type="checkbox" tabindex="-1" id="blahblah-blah" class="k-checkbox">
<span>...</span>
</span>

更新,我也刚刚尝试过;每条评论都无济于事:

Update, I have just tried this as well; per a comment with no avail:

var el = document.querySelector('input[id^="blahblah"]');
el.parentNode.parentNode.click();

推荐答案

closest()方法遍历Element及其其父对象(朝文档根目录前进),直到找到与该元素匹配的节点为止.提供的选择器字符串.将返回自己或匹配的祖先.如果不存在这样的元素,则返回null.

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

您想要获得的实际上是aS1的父级的兄弟姐妹,因此输出为空.

What you desire to get is actually a sibling of the parent of aS1, hence the output is null.

如果代码是这样,您将获得所需的元素.

You would have got the desired element if the code was like this.

<span class="k-icon k-i-collapse">
   ::before
   <span class="k-checkbox-wrapper">
        <input type="checkbox" tabindex="-1" id="blahblah-blah" class="k-checkbox">
        <span>...</span>
   </span>
</span> 

还请注意,没有父类的类名称为"k-i-collapse".

Also note that there was no parent element with class name 'k-i-collapse'.

这篇关于如何在元素父级兄弟选择器上运行.click?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆