找到你要的答案

Q:Javascript click on query selector

Q:在查询选择器JavaScript点击

Here is javascript code.

document.querySelectorAll("li[class='user selected']")

I wanna click on this element but this code does not work

document.querySelectorAll("li[class='user selected']").click();

How can I click on this element ? Thanks.

Edit : this is Html code

<ul class="search" id="typeahead_list_u_0_2" role="listbox">
<li class="user selected" title="Special Username" aria-label="Special Username" role="option" aria-selected="true" id="js_g">
<a href="https://..." rel="ignore" target=""><img alt="" src="https://...">
<span class="text">Special Username</span>
</a>
</li>
</ul>

这里是JavaScript代码。

document.querySelectorAll("li[class='user selected']")

我想点击这个元素,但这个代码不工作

document.querySelectorAll("li[class='user selected']").click();

How can I click on this element ? Thanks.

编辑:这是HTML代码

<ul class="search" id="typeahead_list_u_0_2" role="listbox">
<li class="user selected" title="Special Username" aria-label="Special Username" role="option" aria-selected="true" id="js_g">
<a href="https://..." rel="ignore" target=""><img alt="" src="https://...">
<span class="text">Special Username</span>
</a>
</li>
</ul>
answer1: 回答1:

Have you tried ?

document.querySelectorAll("li[class='user selected']")[0].click();

Will click on the first ([0]) li[class='user selected']

你试过了吗?

document.querySelectorAll("li[class='user selected']")[0].click();

将点击第一个([ 0 ])里[类=用户选择]

answer2: 回答2:

Remove the sample click listener that i have attached.

var element = document.querySelector("li[class='user selected']");

if (element) {
    
    // TODO: Attaching sample click listener. Remove it.
    element.addEventListener('click', function () {
        alert('Clicked');
    }, false);
    
    element.click();

}
<li class="user selected" title="Special User Name" aria-label="Special User Name" role="option" aria-selected="true" id="js_x"></li>

删除我所附的样本点击监听器。

var element = document.querySelector("li[class='user selected']");

if (element) {
    
    // TODO: Attaching sample click listener. Remove it.
    element.addEventListener('click', function () {
        alert('Clicked');
    }, false);
    
    element.click();

}
<li class="user selected" title="Special User Name" aria-label="Special User Name" role="option" aria-selected="true" id="js_x"></li>
javascript  jquery  dom  click  html-lists