Harris Jones
Harris Jones

Reputation: 41

How do i select every last child of a specific class in a list

I have a div which contains a list of other div as messages, I want to select every last child of the div that has the same class.

here is my code:

<p>The first paragraph.</p>
<p class="q">The second paragraph.</p>
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>

All I want is to select every last child of class "q".

Like this:

<p>The first paragraph.</p>
<p class="q">The second paragraph.</p> - Selected
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p> - Selected
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p> - Selected

Please Help no matter if it can be done through css, jQuery or PHP snippet

Upvotes: 1

Views: 46

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

This worked. These are the two selectors.

$("p.q + p:not(p.q)").prev("p");
$("p.q:last");

Or as a single one:

$('p.q + :not(p.q)').prev().add('p.q:last');

Could be complicated, but worth a try:

$(function () {
  $('p.q + :not(p.q)').prev().add('p.q:last').addClass("selected");
});
.selected {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>The first paragraph.</p>
<p class="q">The second paragraph.</p>
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>

Upvotes: 3

Related Questions