Is there any way to select the first child only if there is a second child? I'd like to hide the first <p></p>
tag only if there is a second one. Is there any way to do this with CSS?
My code is this
<div>
<p></p>
<p>something</p>
</div>
You can only do this by combining :first-child
and :nth-last-child()
, which means in pure CSS you won't get any better support than IE9 and later:
p:first-child:nth-last-child(2) {
display: none;
}
If you're looking to hide the first p
when it has siblings at all (i.e. it doesn't matter whether there are 2, 3, 4... children in total), use this instead:
p:first-child:not(:only-child) {
display: none;
}
Does the solution need to be cross-browser compatible? If so, I'm not sure if it can be done with CSS. However, it's easy to accomplish with jQuery:
jsFiddle: http://jsfiddle.net/SVTxD/
$(document).ready(function(){
$('div.myDiv').each(function(){
console.log($(this).children().length);
if ($(this).children('p').length > 1){
$(this).children('p').first().hide();
}
});
});
Alternatively (thank you BoltClock):
$(document).ready(function(){
$('div.myDiv p:first-child:nth-last-child(2)').hide();
});
If jQuery isn't an option (or it doesn't need to work in older browsers), then Josh C's answer is correct.
EDIT: Includedd @BoltClock's suggestion as an alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With