Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!