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. UsequerySelector
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 classuser selected
? Or manyli
elements will have that class ? – Vigneswaran Marimuthu Commented May 4, 2015 at 13:43
2 Answers
Reset to default 2Remove 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']