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

112
Visualizações
Adding HTMLOptGroup dynamically

I'm currently adding options to a select element dynamically like this:

   const jobs = [{...},{...},{...}];
   const jobsInput = document.querySelector(...);

   jobs.forEach(job => {
        const option = new Option(`${job.title}`, job.id);
        jobsInput.add(option, undefined);
    });

I'd like to be able to add an <optgroup> each time a property of the job object (job.companyName) changes. Pretty sure the logic behind that is easy enough, but I don't know the syntax. Mozilla talks of an HTMLOptGroupElement, but I don't know how to use it. When I try I get an illegal constructor error.

I'd have thought you add it like this:

const optGroup = new HTMLOptGroupElement('title');
jobsInput.add(optGroup);
optGroup.label = 'title';

but obviously I'm just making this up and it doesn't work :) I can't find anything explaining how to implement the element. If I had to guess it's because it's an interface, but that still doesn't help me

Thanks

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should use :

 const optGroup = document.createElement('optgroup');

which actually returns an HTMLOptGroupElement.

The Illegal constructor error happens because HTMLOptGroupElement is an interface you can't instanciate by itself (by invoking a constructor with the new keyword), as abstract classes in general for most OO languages.

It is usually preferred to use document.createElement instead of constructors for consistency, because not all HTMLElements have a constructor whereas this method is the generic way to create any HTML element.

Also, note that each option (use document.createElement('option') as well) must be added to its repective optGroup (parent) element, and the optGroups to the parent select element.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use forEach and a simple if.

Just need to keep the current group available - when you append, the group is replaced

HTMLOptGroupElement is created using document.createElement("optgroup");

const jobs = [
{"companyName":"BMW","title":"Director","id":"1"},
{"companyName":"BMW","title":"Service desk","id":"2"},
{"companyName":"Honda","title":"VP","id":"3"},
{"companyName":"Honda","title":"VP1","id":"4"},
{"companyName":"Honda","title":"VP2","id":"5"},
{"companyName":"Fiat","title":"VP","id":"6"},
{"companyName":"Fiat","title":"VP1","id":"7"},
{"companyName":"Fiat","title":"VP2","id":"8"}
];

const sel = document.getElementById("jobSelect");
jobs.forEach(job => {
  let group = sel.querySelector(`optgroup[label="${job.companyName}"]`);
  if (!group) {
    group = document.createElement("optgroup");
    group.label = job.companyName;
  }
  const opt = new Option(job.title, job.id);
  opt.classList.add("colored"); // may not actually do anything in some browsers
  group.append(opt)
  sel.appendChild(group)
})
.colored{ color: red; }
<select id="jobSelect"></select>

Chrome 100 Windows 10 Enterprise

enter image description here

Chrome 100 OSX

enter image description here

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