Select specific element before other element

后端 未结 5 1659
刺人心
刺人心 2020-12-06 04:41

I have following HTML structure:

Candy jelly-o jelly beans gummies lollipop

Cupcake ipsum dolor sit amet.

5条回答
  •  無奈伤痛
    2020-12-06 04:58

    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.

提交回复
热议问题