Select options in drop-down menu using CSS and Javascript
P粉739706089
P粉739706089 2023-09-04 22:10:59
0
1
527
<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>
P粉739706089
P粉739706089

reply all(1)
P粉665427988

There seems to be something wrong with your HTML structure to me. An input element does not contain options; a select element does. My code snippet shows you how to programmatically assign the value of the select 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 but select because semantically Speaking of which, input and options 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.

const select = document.querySelector(".ng-touched > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > select:nth-child(1)")


// setTimeout used to visualize how GOOGLE changes to APPLE.
setTimeout(() => {

  // You can access the options of the select with .options.
  // Then you can programatically set the selected value by index.
  select.options.selectedIndex = 1
}, 2000)
<div class="ng-touched">
  <div style="padding-left: 16px;">

    <div style="padding-left: 16px;">

      <div> </div>
      <div style="padding-left: 16px;">
        <select id="companies">
          <option value="google">GOOGLE</option>
          <option value="apple">APPLE</option>
          <option value="facebook">FACEBOOK</option>
          <option value="amazon">AMAZON</option>
        </select>
      </div>
    </div>
  </div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!