Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's ":last-child" selector won't respect <body> as parent on Jsbin?

I have this simple HTML :

<body>
  <a>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
  </a>
</body>

The divs are children of <a>.

From jQuery :

:last-child Selector — Selects all elements that are the last child of their parent.

Ok , Running this code :

 $("div:last-child" ).css('background-color','red')

Will yield :

enter image description here

Ok , let's remove <a> so that divs will be direct children of the Body

<body>

    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>

</body>

Result : Nothing is painted. (http://jsbin.com/kamepu/4)

Question

Those divs are children of Body. why it is not working ?

NB I know I can use last. but that's not my question.

like image 619
Royi Namir Avatar asked Nov 23 '14 12:11

Royi Namir


People also ask

Why is my last child not working?

:last-child will not work if the element is not the VERY LAST element. In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container.

Why is last child not working CSS?

Pseudo-selectors like :last-child or nth-child or nth-of-type only select based on elements not classes or attributes. Either something is the last-child or it isn't. If it's the last element in a parent it will be selected. So, in your case, it's testing for it to meet all the conditions.

How do you use not your last child in SCSS?

There comes the use of pseudo selectors. This article explains the :not(:last-child):after selector. This selector does not select the element after the last child element. It is mostly used to add the content after every child element except the last.


2 Answers

If you look at the DOM, JS Bin inserts some script elements before the closing </body> tag, which prevents any of the divs from matching div:last-child. Remember that although script elements are (usually) not rendered, they do exist in the DOM just like any other HTML element, and as a result will affect selector matching.

The last div is in fact the last of its type, even if it isn't the very last child of body; you can verify this by switching to :last-of-type and it will match.

As mentioned in the comments, Stack Snippets does this as well:

div:last-child { text-decoration: underline; }
div:last-of-type { color: red; }
<body>
  <div>Red but no underline</div>
</body>
like image 129
BoltClock Avatar answered Oct 19 '22 06:10

BoltClock


:last-child returs true is the very last child is of this type (div in this case).

JSBin links scripts at the bottom of the page (before </body>), so :last-child can works with script element only.

Solution is to move scripts into head section using document.ready or after </body>.

like image 24
pavel Avatar answered Oct 19 '22 07:10

pavel