Display only first child of div

I struggled with finding a way to show only the first child of my div and hide everything else. Can this be done exclusively in css or do I need to enable Javascript?

So, how can I get this to display only the first p-tag?

<div id="test1"> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> </div> 

http://jsfiddle.net/8XYNx/

+4
source share
11 answers

try it

http://jsfiddle.net/8XYNx/10/

CSS

  #test1 p{ display:none; } #test1 p:first-child{ display:block; } 
+7
source

The combination of :not and first-child should do this:

 #test1 p:not(:first-child) { display: none; } 

Note that this will not work in IE until version 9.

+6
source

Using :first-child wrapped in :not() :

Fiddle

 #test1 p:not(:first-child) { display:none; } 

Please note that first-child not supported by IE8 or earlier. If you need full cross-browser support, you will have to use Javascript.

Javascript solution will be:

Fiddle

 var div = document.getElementById("test1"); var pList = div.getElementsByTagName("p"); for(var i=0; i<pList.length; i++) { if(pList[i] != div.children[0]) { pList[i].style.display = "none"; } } 
+3
source
 #test1 p { display: none; } #test1 p:first-child { display: block; } 

http://www.w3.org/TR/CSS2/selector.html#first-child

+2
source

Hiding all the elements of P, and then implicitly displaying the first element of p:

 #test1 p { display: none; } #test1 p:first-child { display: block; } 

Demo

If a DOCTYPE declared, this will work in IE7 +. Check browser compatibility here (as opposed to using :not , which will only work on IE9 if you are not using IE7.js )

+1
source

display: none for each item except the first (1n w / 2 offset).

 #test1 p:nth-child(1n + 2){ display: none; } 

Demo

+1
source

Try it, should work with IE7 +

CSS

 #test1>p ~ p{ display: none; } 

Jsfiddle on

If you need older support, this should be a cross browser.

Javascript

 var test1 = document.getElementById("test1").getElementsByTagName("p"), i = 1, p = test1[i]; while (p) { p.style.display = "none"; p = test1[i += 1]; } 

Jsfiddle on

+1
source
 $('#test1 p:not(:first-child)').hide(); 

Demo

0
source

Look at this url, use the psudo element to select specific elements to apply CSS http://www.w3schools.com/CSS/css_pseudo_elements.asp

0
source

Try

 #test1 p:not(:first-child) { visibility:hidden; } 
0
source

In your example, you used only p elements, but if there are other elements included? In general, to show only the first element, you can use this:

 #test1 :not(:first-child) { display: none; } 

Note that this does not work in IE <9.

A demonstration of the script .

0
source

Source: https://habr.com/ru/post/1490892/


All Articles