1

I want to select an element if and only if its adjacent sibling is a certain element.

<div>
    <h1>Select Me</h1>
    <h2>I'm the sibling, yay!</h2>
    <div>
        <p>A paragraph.</p>
    </div>
</div>
<div>
    <h1>Don't Select Me - I have no h2 sibling. :(</h1>
    <div>
        <p>A longer paragraph.</p>
    </div>
</div>

In this particular example, I only want to select the first h1 because it has an adjacent h2. The other h1 doesn't meet that criteria so I don't want it selected.

I found this but it won't work for me because the element has other siblings and is never an only child.

Community
  • 1
  • 1
dokgu
  • 4,957
  • 3
  • 39
  • 77

1 Answers1

1

There is no previous element selector in CSS yet. There is a adjacent sibling selector: + and there is a general sibling selector: ~.

Thought I can give you a jQuery solution:

$('h2').prev('h1').addClass('favH1');
h1.favH1{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <h1>Select Me</h1>
    <h2>I'm the sibling, yay!</h2>
    <div>
        <p>A paragraph.</p>
    </div>
</div>
<div>
    <h1>Don't Select Me - I have no h2 sibling. :(</h1>
    <div>
        <p>A longer paragraph.</p>
    </div>
</div>
Roy
  • 1,939
  • 1
  • 14
  • 21
  • 1
    I would make it more specific, like this: `$('h2').prev('h1').addClass('favH1');` otherwise any other element that might be behind any `h2` tag will get that styling... – Aziz Apr 07 '16 at 20:53
  • @Aziz thanks! Updated the code! – Roy Apr 07 '16 at 21:00
  • I'm upvoting but I can't really accept the answer as the question is with regards to CSS. This works though. Putting a class before the page was rendered was an easier solution for me. Thanks anyway! – dokgu Apr 07 '16 at 21:21