JavaScript: how to hide the option element in mobile browsers

In mobile browsers, hiding an option element requires JavaScript.

Mobile browsers do not allow you to hide a option element using the hidden attribute. There are therefore two solutions in JavaScript to work around this problem.

The first involves removing the elements, filtering and restoring.


'use strict';

const select = document.querySelector('#select');
const originalSelectHTML = select.innerHTML; // For restoring

select.querySelectorAll('option').forEach(option => {
   if(option.value === 'B') {
       option.remove();
   }
});

The second is to insert options into other elements and then work with CSS on their parents.


'use strict';

const select = document.querySelector('#select');

select.querySelectorAll('option').forEach(option => {
   let parent =  document.createElement('div'); 
   if(option.value === 'B') {
       option.parentNode.insertBefore(parent, option);
       parent.appendChild(option);
   }
});

Then with CSS:


#select div {
    display: none !important;
}

Back to top