问题
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