How to hide the first and last element of three identical elements

I have three divs with the same class name, I want to hide the first and last div.

My code:

<div class="clsname">div1</div>
<div class="clsname">div2</div>
<div class="clsname">div3</div>

      

Now I want to hide div1 and div3. Actually I want this output in the browser:

div2

      

How can i do this?

To clarify, I want something like this: (this will only hide div3)

div.clsname + div.clsname + div.clsname {display:none;}

      

+3


source to share


5 answers


Use this simple CSS:

div.clsname:first-child, div.clsname:last-child{
    display:none;
}

      



FIDDLE: https://jsfiddle.net/lmgonzalves/aLaw2qj5/

+2


source


You can achieve this by doing

var elements = jQuery(".clsname");
for (var i = 0 ; < elements.length; i++) {
     if( i == 0 || i = elements.length -1) {
           jQuery(element[i]).style("display" : "none");
     }

}

      



This will hide the first and last elements with a specific class.

+3


source


lmgonzalves might be a valid answer. But you are not showing all your markup, so Hashem Qolami is right, this might not be what you want.

Maybe a better solution could be

.clsname, .clsname + .clsname + .clsname { display: none;}
.clsname + .clsname { display: block;}

      

+2


source


div.clsname:first-child{
  display:none;
}

div.clsname:last-child{
 display:none;
}

      

+1


source


Here is a solution that targets only three divs with a class and leaves the rest of the divs alone. (So ​​it works either with or without other divs in between.)

div.clsname, div.clsname ~ div.clsname ~ div.clsname {display:none}
div.clsname ~ div.clsname {display:block}
      

<div>Other div, displayed normally</div>
<div class="clsname">div1</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
<div class="clsname">div2</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
<div class="clsname">div3</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
<div>Other div, displayed normally</div>
      

Run codeHide result


Compatible with all modern browsers and even IE8.

+1


source







All Articles