Akheloes
Akheloes

Reputation: 1372

Exclude an element in descendant selector?

I am wondering if there is any way of excluding an element after selecting a descendancy. Let's say we have this DOM :

    <div class="container">
      <p></p>
      <p></p>
        .
        .
        .
      <p></p>
      <p></p>
    </div>

Now, if we use the selectors like this :

$('.container p')

We'll get all the <p> tags/objects (let's say they are n tags/objects). What if I want to exclude the k-ranked p-tag/objects ? Therefore having my selector return only n-1 p-tags/objects ?

P.S : you might recommand to use the id attribute, but let's suppose I can't add an id to all the p-tags and that I might want to exclude the k or j ranked p-tag, at wish. Also, I know that this might be doable in JavaScript, but I am searching for a jQuery specific answer (though JavaScript might be good as a last resort).

k-ranked : k-ranked p-tag/object will be the k'th positionned p-tag starting count from 1 :

      <p></p>  <---> 1
      <p></p>  <---> 2
        .
        .
      <p></p>  <---> k 
        .
        .
      <p></p>  <---> n-1
      <p></p>  <---> n

Thanks.

Upvotes: 0

Views: 110

Answers (2)

Vivek Sadh
Vivek Sadh

Reputation: 4268

If you want to apply a style to some elements and you want to exclude some kth element of that type then you can use this:-

$( document ).ready(function() {
$("p:not(:eq(2))").css("border", "3px solid red");
    });

JS FIDDLE

Upvotes: 1

webrama.pl
webrama.pl

Reputation: 1890

Maybe something like that:

var $elements = $("div.container > p:not(:eq(2))");

But say something more about "n", "j", "k" indexes.

Upvotes: 1

Related Questions