Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda