Javascript select from tag select by text

I have to make javascript, select from one of this options by the text that is written,(Small, Medium, Large, Xlarge)
not by the value, can someone please help me 🙂

<option value="s">Small</option>
<option value="M">Medium</option>
<option value="L">Large</option>
<option value="XL">XLarge</option>
</select>

5 thoughts on “Javascript select from tag select by text”

  1. This creates the exact same that you provided, just add more options.

    let options = [{ name: 'small', value: 's' }, { name: 'medium', value: 'm' }]
    var dropdown = document.createElement('select');
    document.querySelector('body').appendChild(dropdown)
    
    function addOpt(option, parentElement) {
        var opt = document.createElement('option');
        opt.setAttribute('value', `${option.value}`)
        opt.innerText = option.name
        parentElement.appendChild(opt)
    }
    
    options.forEach(option =>
        addOpt(option, dropdown)
    )
    
    Reply
  2. document.querySelectorAll("select option").forEach(option => {
      option.text === "Medium" ? option.selected=true  : option;
    })
    <select>
      <option value="s">Small</option>
      <option value="M">Medium</option>
      <option value="L">Large</option>
      <option value="XL">XLarge</option>
    </select>
    Reply

Leave a Comment