Home > Mobile >  Adding HTMLOptGroup dynamically
Adding HTMLOptGroup dynamically

Time:04-18

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 enter image description here

Chrome 100 OSX

enter image description here

CodePudding user response:

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.

  • Related