仅显示div的第一个子节点

时间:2013-07-11 12:02:55

标签: javascript css css-selectors

我一直在努力寻找一种方法来只显示我的div的第一个孩子并隐藏所有其余的孩子。这可以纯粹用css完成,还是我必须涉及一些Javascript?

那么,我怎样才能让它只显示第一个p-tag?

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

http://jsfiddle.net/8XYNx/

11 个答案:

答案 0 :(得分:9)

试试这个

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

CSS

  #test1 p{
    display:none;

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

答案 1 :(得分:6)

:notfirst-child的组合肯定会这样做:

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

请注意,这在版本9之前的IE中不起作用。

答案 2 :(得分:3)

使用:first-child中包含的:not()

Fiddle

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

请注意,IE8或更早版本不支持first-child。如果您需要完整的跨浏览器支持,则必须使用Javascript。

Javascript解决方案将是:

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 :(得分:2)

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

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

答案 4 :(得分:1)

隐藏所有P元素,然后隐式显示第一个p元素:

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

DEMO

如果声明了DOCTYPE,这将在IE7 +中起作用。检查浏览器兼容性here(与will only work in IE9使用:not不同,除非您使用IE7.js

答案 5 :(得分:1)

display: none除了第一个(1n w / 2偏移)之外的每个元素。

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

<强> DEMO

答案 6 :(得分:1)

试试这个,should work with IE7+

CSS

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

jsfiddle

如果您需要较旧的支持,那么这应该是跨浏览器。

的Javascript

var test1 = document.getElementById("test1").getElementsByTagName("p"),
    i = 1,
    p = test1[i];

while (p) {
    p.style.display = "none";
    p = test1[i += 1];
}

jsfiddle

答案 7 :(得分:0)

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

Demo

答案 8 :(得分:0)

看一下这个URL,使用伪元素选择要应用CSS的特定元素 http://www.w3schools.com/CSS/css_pseudo_elements.asp

答案 9 :(得分:0)

尝试

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

答案 10 :(得分:0)

在您的示例中,您仅使用p元素,但是如果还包含其他元素?通常,要仅显示第一个元素,您可以使用:

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

请注意,这在IE&lt; 9。

中不起作用

A fiddle demo

相关问题