Search code examples
jquerycss-selectorspseudo-class

.first() works, but not :first-child or :odd


I got a bunch of .tileItem elements in my DOM tree. I want to give the 1,3,5,7,... element a margin-right.

The problem is, when I select the elements like this it does not work:

$(".tileItem:odd").css("margin-right","2%");

This works neither:

$(".tileItem").find(":odd").css("margin-right","2%");

I was curious and tried the following:

$(".tileItem:first-child").css("margin-right","2%");

No luck at all.

Here comes the interesting part: When I try this:

$(".tileItem").first().css("margin-right","2%");

It works like a charm. Of course only the first element gets set, but why does this work and all the other selectors fail?


Solution

  • .first() returns the first element in the set and not necassarily the first child

    See docs: http://api.jquery.com/first/

    Depending on what your html looks like, but if you want the children how would this work:

    $('.tileItem').children(':even').css("margin-right","2%")
    

    Note that because of zero-based indexing, :odd actually selects the second element, fourth element, etc. That is, the odd index number 1,3,5... That's why I've used :even to select the first, third, etc. element as per your question.

    jQuery docs on :odd and :even

    This can be a bit confusing.