Sam
Sam

Reputation: 2545

Target elements that come after a specific element with CSS/JS

Using Javascript/jQuery or a CSS selector, how would I target elements that come after a specific element? To be clear, I don't mean directly after (adjacent to), I mean any and all matching elements that exist further down the page.

Imagine a group of <p>s:

<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

Now I want to target all of the <p>s that come after p#special... so the ones with content "Dolor", "Sit", and "Amet". I want there to be some selector available like:

$('p#special::allAfter p').each(...

How would I do this?

Upvotes: 0

Views: 106

Answers (5)

Jacob G
Jacob G

Reputation: 14172

If all the elements are in the same parent, you can just use the General Sibling Combinator ~:

#special ~ p {
  color: red;
}
<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

However, then the <p> does have to be a sibling.

Otherwise, if you want to select every p further down the page, no matter if it's a sibling or not, you'll have to use JS:

var para = document.querySelectorAll("p"), //Get p's
  addColor = false;

Array.prototype.forEach.call(para, function(p) {
  //Loop through paragraphs

  //If addColor is true, add color to paragraph
  if (addColor) p.style.color = "red";

  //If the current paragraphs id is special, set addColor to true
  if (p.id == "special") addColor = true;
});
<div>
  <p>Test</p>
  <p>Test</p>
  <p id="special">Test</p>
</div>
<p>Test</p>
<p>Test</p>
<div>
  <div>
    <p>Test</p>
  </div>
</div>

Or, in jQuery:

var para = $("p"),
  addColor = false;

para.each(function() {
  if (addColor) this.style.color = "red";
  if (this.id === "special") addColor = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <p>Test</p>
  <p>Test</p>
  <p id="special">Test</p>
</div>
<p>Test</p>
<p>Test</p>
<div>
  <div>
    <p>Test</p>
  </div>
</div>

Upvotes: 0

Fabian S.
Fabian S.

Reputation: 2529

You can use the CSS ~ selector.

In your case:

p#special ~ p

Upvotes: 0

adeneo
adeneo

Reputation: 318212

You could use the general sibling selector in CSS

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

#special ~ p {color: red}
<p>Lorem</p>
<p id="special">Ipsum</p>
<p>Dolor</p>
<p>Sit</p>
<p>Amet</p>

In jQuery it's called the "Next Siblings Selector "

$('#special ~ p')

Upvotes: 3

user3155561
user3155561

Reputation:

jQuery

next() https://api.jquery.com/next/

nextall() https://api.jquery.com/nextAll/

nextuntil() https://api.jquery.com/nextUntil/ (Might more useful)

$( "p#special" ).next().css( "background-color", "red" );

Upvotes: 0

Aakash Thakur
Aakash Thakur

Reputation: 3895

nextAll() is a jQuery function that you are looking for.

See this documentation:https://api.jquery.com/nextAll/

Upvotes: 2

Related Questions