Select options in drop-down menu using CSS and Javascript
P粉739706089
2023-09-04 22:10:59
<p>I have a CSS selector value: </p>
<pre class="brush:php;toolbar:false;">.ng-touched > div:nth-child(1) > div:nth-child(1) > div:nth-child(2 )> input:nth-child(1)</pre>
<p>I'm trying to use document.querySelectorAll to find this CSS selector that has a dropdown menu, <strong>and select the option with the text "APPLE"</strong>. It's the second option in the drop-down menu.
To do this I am using the following code but after running the code the option "APPLE" is not selected: </p>
<pre class="brush:php;toolbar:false;">document.querySelectorAll(".ng-touched > div:nth-child(1) > div:nth-child(1) > div :nth-child(2) > input:nth-child(1)")
.forEach(o => {
o.value = "APPLE";
});</pre>
<p>Please guide me what is going wrong and what necessary changes should be made to the code. Thank you in advance. </p>
There seems to be something wrong with your HTML structure to me. An
input
element does not containoptions
; aselect
element does. My code snippet shows you how to programmatically assign the value of theselect
dropdown menu to the second option, which is APPLE.It also uses your existing structure (derived from your query), but the last element no longer uses
input
butselect
because semantically Speaking of which,input
andoptions
are not logical. So, if my explanation is wrong, my solution may not accurately answer your question. But I hope it still guides you in the right direction.