How to target the first-child of an optgroup with

2019-08-10 12:56发布

问题:

Is there a way to target the first-child of the optgroup labeled "Portfolio" displaying the name "Main"?

I need to remove it from showing only in a mobile menu (it doesn't display in the desktop menu). This is a Wordpress theme menu that is not accessible by Menus widget. The menu is created by a mobilemenu.js triggered by media query (I guess). It is displaying the Home page by 2 different names/menuitems. I was hoping to target just that menuitem and use a css display:none or a jQuery getElementByID solution but so far have had no luck. In a bit over my head on this one as I cannot seem to target it. Any help would be greatly appreciated!

<div class="mobilenavi">
  <select id="mm0" class="mnav" style="display: inline-block;">
    <option value="undefined">Click here:</option>
    <option value="http://somedomain.com/">Home</option>
    <optgroup label="Portfolios">
      <option value="#">Main</option>
      <option value="http://somedomain.com/portfolio-1/">Portfolio 1</option>
      <option value="http://somedomain.com/portfolios/portfolio-2/">Portfolio 2</option>
      <option value="http://somedomain.com/portfolios/portfolio-3/">Portfolio 3</option>
      <option value="http://somedomain.com/portfolios/beach-portfolio/">Beach Portfolio</option>
      <option value="http://somedomain.com/portfolios/photos/">Photos</option>
    </optgroup>
    <option value="http://somedomain.com/contact/">Contact Kim</option>
  </select>
</div>

回答1:

This CSS approach would work in some browsers:

Example Here

optgroup[label="Portfolios"] option:first-child {
    display:none;
}

As @canon points out, display:none won't work in all browsers though.

If you want to remove it with jQuery, use:

Example Here

$('optgroup[label="Portfolios"] option:first-child').remove();

Alternatively, if you want a pure JS approach:

Example Here

var el = document.querySelector('optgroup[label="Portfolios"]');
el.removeChild(el.getElementsByTagName('option')[0]);


回答2:

Does $('optgroup option:nth-child(1)').hide(); work?