How to Select All Children of an Element Except the Last Child?

To select all children of an element except the last child, we can use the :not() selector in combination with the :last-child selector.

The :last-child selector allows you to target the last child of its parent and the :not() selector allows you to prevent certain elements from being selected.

So, if we select only the last child and put a negation(:not) before it, we will get the desired result. This is the concept we are going to use.

So, for example, if we want to select all children of a div element except the last, we will have to use div :not(:last-child).

See the implementation below:

Example:

div :not(:last-child){
   background-color: yellow;
}

While applying the :not() selector, it is to be remembered that you have specified the parent element before the :not(). As in our case, we have put a div before :not(:last-child).

If you do not specify the parent element before the :not() selector, it will target every last child of its parent which includes the <body> tag also. This might cause some unexpected results.

See the following example where we have not put any parent element before the :not() selector. Therefore, it selects the <body> tag as well and hence makes the whole document yellow:

Example:

:not(:last-child){
   background-color: yellow;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts