how to run a .click on elems parent sibling selector?

☆樱花仙子☆ 提交于 2020-06-01 05:06:48

问题


Below is my most recent attempt:

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

It returned:

myjs.js:181 Uncaught TypeError: Cannot read property 'closest' of null

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

Below is my mark-up:

<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();

回答1:


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.

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> 

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




回答2:


As said on the comment, it seems you are mixing jquery's API with DOM API, stick to one of them and you'll get the result (assuming that the selector for blahblah actually finds an object)



来源:https://stackoverflow.com/questions/62029135/how-to-run-a-click-on-elems-parent-sibling-selector

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