Change element property based on placement of another element - jQuery

319 views Asked by At

I'm having trouble working out how I can target a super annoying edgecase I'm having.

How can I target the h1, that comes after the cite tag? As cite is wrapped inside the p tag, I don't know how to traverse out to target it.

The gap between the cite (technically the p) is too large, yet on 'non-cite' paragraphs, it is fine.

TL:DR - Check if a paragraph has a cite tag inside of it, then if it does - change the padding-top on the h1 tag to something less. If the paragraph doesn't have a cite inside, leave it untouched.

http://codepen.io/anon/pen/Jksam

HTML

<link href='http://fonts.googleapis.com/css?family=Lato:400,900' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Gentium+Book+Basic:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

<div class="post">
    <blockquote>
      <p>
          “Work is the curse of the drinking classes.”
      </p>
    </blockquote>

    <p>
      <cite>
          Oscar Wilde
      </cite>
    </p>

    <h1>
       This is a H1
    </h1>

    <p>
       Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
    </p>

    <h1>
       This is a H1
    </h1>
</div>

CSS

.post {
  width: 50%;
  padding-left: 25%;
  padding-top: 3rem;
}

h1 {
  color: #333332;
  font-family: 'Lato', sans-serif;
  padding-top: 1.5rem;
  padding-bottom: 1rem;
  font-weight: 900;
  font-size: 3.3rem;
}

p + h1 {
  padding-top: 4rem;
}

blockquote {
  border-left: 4px solid #ED5565;
  margin-left: -24px;
  margin-top: -1px;
}

cite {
  color: #b3b3b1;
  font-family: 'Lato', sans-serif;
  font-weight: 400;
  font-size: 0.8rem;
  position: relative;
  top: -15px;
  padding: 0;
  margin: 0;
}

cite:before {
  content: "- ";
}

blockquote > p {
  padding: 1em; 
  margin: 0;
}

p {
  color: #333332;
  font-family: 'Gentium Book Basic', serif;
  font-weight: 400;
  font-size: 1.5rem;
  line-height: 1.8rem;
  padding-bottom: 1rem;
  padding-top: 1rem;
}
2

There are 2 answers

1
Ram On BEST ANSWER

You can use .has() method or :has selector:

$('p').has('cite').next('h1').css({'padding-top': 'value'});

Assuming all next h1 siblings of the selected p should be selected:

$('p').has('cite').nextAll('h1').css({'padding-top': 'value'});
0
wirey00 On

another way would be to start from the cite tag using then use .closest() to get to the p tag - then get the next h1 element

$('cite').closest('p').next('h1').css('padding-top','50px')