Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda