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;}
Use this simple CSS:
div.clsname:first-child, div.clsname:last-child{
display:none;
}
FIDDLE: https://jsfiddle.net/lmgonzalves/aLaw2qj5/
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.
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;}
div.clsname:first-child{
display:none;
}
div.clsname:last-child{
display:none;
}
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>
Compatible with all modern browsers and even IE8.