Home > other >  CSS - Hide every element of the same kind except the first - not child
CSS - Hide every element of the same kind except the first - not child

Time:03-21

I've been trying to figure out the way to hide every 'label' element in the html below except the first one. I've got a repeater field that adds a row with a dropdown select field and a label.

Each new row adds the select field and the label. The label id starts with 'label-repeat- ' and the suffix is dynamically generated based on the number of repeater rows, so it goes: 'label-repeat-1', 'label-repeat-2', 'label-repeat-3' etc.

The issue is that each repeater row is separately wrapped into its own div, so I'm guessing I cannot use :not(:first-child) in the case.

Here is my fiddle and below is my html:

<div >
  <div >
   <label id="label-repeat-1" >Status</label>
   <select id="field-repeat-1" >
     <option value="Open">Open</option>
     <option value="Closed">Closed</option>
   </select>
  </div>
</div>
<div >
  <div >
   <label id="label-repeat-2" >Status</label>
   <select id="field-repeat-2" >
     <option value="Open">Open</option>
     <option value="Closed">Closed</option>
   </select>
  </div>
</div>
<div >
  <div >
   <label id="label-repeat-3" >Status</label>
   <select id="field-repeat-3" >
     <option value="Open">Open</option>
     <option value="Closed">Closed</option>
   </select>
  </div>
</div>

I've been trying to use the wildcard selector to select the label with label[id^='label-repeat-'], label[id*=' label-repeat-'] which works fine, but then I'm trying to add the :nth-of-type(n 2) pseudo class to select every label except the first one and hide it, but that doesn't seem to work.

label[id^='label-repeat-']:nth-of-type(n 2),
label[id*=' label-repeat-']:nth-of-type(n 2) {
  display: none !important;
}

Is there any other way to do this with CSS? Or even jQuery?

CodePudding user response:

If I understand, you want to hide all except for the first label. So, you would end up with a label and 3 select boxes under it? Using the "plus" combinator in CSS is the easiest way of saying "all but the first one"...

.fieldset   .fieldset label {
  display:none;
}

This rule is saying any fieldset that is followed by another fieldset (all but the first one), then the nested label under those.

  • Related