简体   繁体   中英

Click on Button Class or Span class

I want to simulate a click on a button up or down,

I tried with this : document.querySelector('button.up')[4].click();

in the page there is few input field with up and down button, I would like the button up of the field with id "sl" or nth up button ? the code :

<div class="input-text num" >
<input type="text" placeholder="" id="sl" min="0" max="" step="0.00001">
<button tabindex="-1" class="up">
<span class="v"></span></button><
button tabindex="-1" class="down">
<span class="v"></span></button></div>

The first thing that's likely to cause a problem is this line:

document.querySelector('button.up')[4].click();

The reasons this causes a problem is that document.querySelector() returns either the first element matching the supplied selector or null , if there are no elements matching the selector. Therefore index notation the [4] is destined to fail by design.

Without seeing more of your HTML it's hard to offer a fully working suggestion, but I'd suggest that using an alternative selector should work (so long as your id attributes are unique, as they must be be according to the spec):

document.querySelector('#sl + button.up').click();

 const clickHandler = (event) => { console.log(`${event.target.outerHTML}`); } document.querySelectorAll('button').forEach( (button) => button.addEventListener('click', clickHandler) ); document.querySelector('#sl + button.up').click(); 
 <div class="input-text num"> <input type="text" placeholder="" id="sl" min="0" max="" step="0.00001"> <button tabindex="-1" class="up"> <span class="v">up</span></button> <button tabindex="-1" class="down"> <span class="v">down</span></button> </div> 

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM