Search code examples
javascripthtmlselectoptgroup

How to select all options within an optgroup?


I am wondering what the easiest way to select all options within a single optgroup is?

My understanding is that optgroup labels themselves cannot be selected, so my current implementation has an option element immediately following each optgroup label that says something like "All Options in this optgroup". I'm able to detect the event when this "All" option is selected, but I'm lost after that point. Is this the right path to head down, or am I making this harder than it needs to be?


Solution

  • Use the attribute selector:

    '[attribute name = "value"]'
    
    const groupA = document.querySelector('[label="A"]');
    

    /* 
    Using .querySelectorAll() to collect all of optgroup A options into a NodeList
    */
    const groupA = document.querySelector('[label="A"]');
    
    const allOptA = groupA.querySelectorAll('option');
    
    allOptA.forEach(opt => opt.style.color = 'tomato')
    
    /*
    Using .children and spead operator [...x] to get all options from optgroup B 
    into an Array
    */
    const groupB = document.querySelector('[label="B"]');
    
    const allOptB = groupB.children;
    
    [...allOptB].forEach(opt => opt.style.color = 'lime');
    
    // Gather all optgroups into an Array
    const allGroups = [...document.querySelectorAll('optgroup')];
    
    // Gather each optgroups' options into a sub-array
    const allOpts = allGroups.flatMap(grp => [grp.querySelectorAll('option')]);
    
    // Get the value of the first optgroup  third option
    console.log(allOpts[0][2].value);
    <select>
      <optgroup label='A'>
        <option value='0'>0</option>
        <option value='2'>2</option>
        <option value='4'>4</option>
      </optgroup>
      <optgroup label='B'>
        <option value='1'>1</option>
        <option value='3'>3</option>
        <option value='5'>5</option>
      </optgroup>
    </select>