if it has
with a cl...">

JQuery: add styling for tag if exists above itself

I want .addClass("someClass"

before <blockquote>

if it has <figure>

with a class hello

above it, for example:

<figure class="hello"> world </figure>
<blockquote> Lorem </blockquote>

      

So, only if the tag <figure>

is right above it, not if something is separating tags like div.

Is it possible?

+3


source to share


3 answers


Assuming this is the style of the element <blockquote>

when immediately preceded <figure>

, then you can simply use CSS:

figure + blockquote {
    border-color: red; /* or whatever */
}

      



section {
  border: 1px solid #000;
  margin: 0 0 1em 0;
}

blockquote {
  border: 1px solid #000;
}

figure + blockquote {
  border-color: #f00;
}
      

<section>
  <figure>This is a figure</figure>
  <blockquote>And this is an immediately-following blockquote.</blockquote>
</section>

<section>
  <blockquote>This is a blockquote.</blockquote>
  <figure>And this is a figure following a blockquote</figure>
</section>

<section>
  <figure>Another figure</figure>
  <div>a div</div>
  <blockquote>And this is a blockquote.</blockquote>
</section>
      

Run codeHide result


Literature:

+5


source


$('figure.hello + blockquote').addClass('someClass');

      

From the jQuery docs:



Next adjacent selector ("prev + next")

Selects all next elements matching "next" that immediately preceded the sibling "prev".

+4


source


Can work from a known class ... the simplest

$('figure.hello').next('blockquote').addClass("someClass");

      

How does it work, if any selector is not found, nothing happens and will only work for a figure with the next sibling being a block comment

+3


source







All Articles