最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript click on query selector - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question edited May 4, 2015 at 16:05 El Juego asked May 4, 2015 at 13:08 El JuegoEl Juego 191 silver badge7 bronze badges 7
  • querySelectorAll will return you array of selected element. Not the first match. Use querySelector instead – Vigneswaran Marimuthu Commented May 4, 2015 at 13:09
  • Actually it works fine when I want to return first element but the problem is click event, I can not click . – El Juego Commented May 4, 2015 at 13:12
  • If you add HTML code, i can have a look at it and can suggest. Try to put the code in fiddle and share it. – Vigneswaran Marimuthu Commented May 4, 2015 at 13:13
  • I have updated html code, do you want me to add more html codes ? – El Juego Commented May 4, 2015 at 13:40
  • This is good enough. So, at time, you will have only one li element with class user selected ? Or many li elements will have that class ? – Vigneswaran Marimuthu Commented May 4, 2015 at 13:43
 |  Show 2 more ments

2 Answers 2

Reset to default 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>

Have you tried ?

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

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

发布评论

评论列表(0)

  1. 暂无评论