user4174706
user4174706

Reputation:

Two consecutive pseudo selectors in jQuery don't work

I have some issues selecting an element with jQuery.

my HTML code comes down to:

<body>
  <p>Dont mind me, sir</p>
  <p>Select me please!</p>
  <p class="fabulous">So fab</p>
</body>

with some jQuery:

$(document).ready(function(){
  $('p:not(.fabulous):last-child').css({'background':'yellow'});
});

With the selector $('p:not(.fabulous):last-child') I am trying to select the last element of its parent (body, in this case) that does not have class "fabulous". With $('p:not(.fabulous)') I select all non-fabulous children of body but why can I not select the last child of the leftover p elements? I'd very much appreciate an answer concerning the behaviour of :last-child and :not(, or whatever selector I misunderstood.

Thanks!

Upvotes: 1

Views: 378

Answers (2)

gen_Eric
gen_Eric

Reputation: 227230

:last-child selects all elements that are the last child of their parent. The last (<p>) child of the <body> is <p class="fabulous">.

So, when you do p:not(.fabulous):last-child, you are asking for a <p> that is both the last child of its parent and doesn't have the class fabulous. No such element exists.

You'd need to use $('p:not(.fabulous):last') in this case.

Upvotes: 1

Lochemage
Lochemage

Reputation: 3974

Try $('p:not(.fabulous):last').css({'background-color':'yellow'}); or $('p:not(.fabulous)').last().css({'background-color':'yellow'}); instead

Upvotes: 1

Related Questions