在其他元素之前选择特定元素

问题描述:

我有以下HTML结构:

I have following HTML structure:

<div>
  <h2>Candy jelly-o jelly beans gummies lollipop</h2>
  <p>
    Cupcake ipsum dolor sit amet. Sugar plum liquorice dragée oat cake cupcake.
  </p>
  <p>
    Candy tiramisu bonbon toffee. Croissant pudding ice cream soufflé pastry toffee  chocolate bar. Tiramisu wypas tootsie roll icing fruitcake oat cake icing soufflé tiramisu. 
  </p>
  <h2>Dessert pie cake</h2>
  <ul>
    <li>liquorice</li>
    <li>powder</li>
    <li>dessert</li>
  </ul>
  <h2>Chupa chups sweet dragée</h2>
  <p>
    Chocolate cake biscuit pie jelly-o chocolate bar. Marshmallow topping sugar plum apple pie brownie cotton candy dragée lemon drops. Soufflé cake toffee.
  </p>
</div>

我只想选择 h2 其直接在 ul 之前。我如何做到这一点?在我的内容中有更多 uls 和更多 h2s ,所以解决方案应该是通用的。

I would like to choose only that h2 which is directly before ul. How can I do this? In my content there are many more uls and many more h2s so the solution should be universal.

据我所知,CSS不提供任何选择器,其将定位之前的 选择器。你可以选择 h2 ,它直接在 p p + h2 )?

As far as I know, CSS doesn't offer any selectors which will target before a selector. Could you select it as an h2 which is directly after a p (p + h2)?

h2 {
    color: #1a1a1a;
}

p + h2 {
    color: #0cc;
}

在JSFiddle上的例子

正如你所看到的,这可能是最好的选择器,如果你依靠CSS ,尽管您可以轻松地为每个 h2 添加一个类,该类位于 ul 之前。这将避免你在另一个 h2 和段落前有一个段落的情况。

As you can see, this is probably the best selector you can use if you're relying on CSS, although you could easily just add a class to each h2 that is before a ul. That would avoid the case where you have a paragraph section before another h2 and paragraph section.

使用jQuery:

.highlight {
    color: #0cc;
}

$('ul').prev('h2').addClass('highlight')

JSFiddle示例

这选择每个 ul ,然后选择它之前的 h2 ,最后添加 .highlight 类。

This selects every ul, then selects the h2 that is before it, before finally adding the .highlight class to it.