如何选择第一个相邻的兄弟姐妹? [英] How do I select the first adjacent sibling?

查看:94
本文介绍了如何选择第一个相邻的兄弟姐妹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的HTML列表:

I have an HTML list like so:

<ul>
  <li class="heading">Heading 1</li>
  <li class="heading">Heading 2</li>
  <li>Text Under Heading 2</li>
</ul>

由于标题1下没有文字,我想用CSS隐藏它.

Since Heading 1 has no text under it, I want to hide it with CSS.

如果我这样做,

li.heading + li.heading { display: none; }

它隐藏标题2而不是标题1.

it hides Heading 2 instead of Heading 1.

如何隐藏标题1?有没有办法寻找相邻的兄弟姐妹并选择第一个兄弟姐妹?

How can I hide Heading 1? Is there a way to look for adjacent siblings and select the first one?

推荐答案

无法使用当前定义和实现的CSS.它将需要一个选择器,该选择器根据元素在其后的同级元素来选择元素. CSS选择器可以根据前面的元素或外部元素来选择元素,而不能根据后面的元素或内部元素来选择.

It is not possible using CSS as currently defined and implemented. It would require a selector that selects an element on the basis of its siblings after it. CSS selectors can select an element on the basis of preceeding or outer elements, but not on the basis of following or inner elements.

使用JavaScript可以以一种非常直接的方式实现所需的效果,并且可以根据目的决定是从显示中删除元素还是从文档树中完全删除它们.

The desired effect can be achieved using JavaScript in a rather straightforward way, and you can decide, depending on the purpose, whether you just remove the elements from display or completely remove them from the document tree.

这篇关于如何选择第一个相邻的兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆