Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

css - Select specific element before other element

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>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

Example on JSFiddle

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.

You could do this using jQuery:

.highlight {
    color: #0cc;
}

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

Example on JSFiddle

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...