How to get last child in javascript


HTML DOM Element lastChild Property

❮ Previous ❮ Element Object Reference Next ❯

Example

Return the HTML content of the last child node of an <ul> element:

document.getElementById("myList").lastChild.innerHTML;

Try it Yourself »

Get the text of the last child node of a <select> element:

let text = document.getElementById("mySelect").lastChild.text;

Try it Yourself »

More examples below.


Definition and Usage

The lastChild property returns the last child node of a node.

The lastChild property returns returns a node object.

The lastChild property is read-only.

Important!

lastChild returns the list child node: An element node, a text node, or a comment node.

Whitespace between elements are also text nodes.

Alternative:

The lastElementChild Property

The lastElementChild property returns the last child element (ignores text and comment nodes).

See Also:

The childNodes Property

The firstChild Property

The nextSibling Property

The previousSibling Property

Node Properties

The parentNode Property

The nodeName Property

The nodeType Property

The nodeValue Property

Nodes vs Elements

In the HTML DOM terminology:

Nodes are all nodes (element nodes, text nodes, and comment nodes).

Whitespace between elements are also text nodes.

Elements are only element nodes.


childNodes vs children

childNodes returns child nodes (element nodes, text nodes, and comment nodes).

children returns child elements (not text and comment nodes).


firstChild vs firstElementChild

firstChild returns the first child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

firstElementChild returns the first child element (not text and comment nodes).


lastChild vs lastElementChild

lastChild returns the last child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

lastElementChild returns the last child element (not text and comment nodes).


Syntax

element.lastChild

or

node.lastChild

Return Value

Type Description
NodeThe last child of a node.
nullif no child exists.


More Examples

This example demonstrates how whitespace may interfare:

Try to get the node name of the last child node of "myDIV":

<div>
  <p>Looks like first child</p>
  <p>Looks like last Child</p>
</div>

<script>
let text = document.getElementById("myDIV").lastChild. nodeName;
</script>

Try it Yourself »

However, if you remove the whitespace from the source, there are no #text nodes in "myDIV":

<div><p>First child</p><p>Last Child</p></div>

<script>
let text = document.getElementById("myDIV").lastChild.nodeName;
</script>

Try it Yourself »


Browser Support

element.lastChild is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes 9-11 Yes Yes Yes Yes

❮ Previous ❮ Element Object Reference Next ❯


COLOR PICKER



Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3. CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial

Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference

Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples


FORUM | ABOUT

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2022 by Refsnes Data. All Rights Reserved.
W3Schools is Powered by W3.CSS.

javascript - Second last child without jquery

Asked

Modified 1 year, 10 months ago

Viewed 7k times

I am trying to find a way to select #inner3

 <div> <div> </div> <div> </div> <div> of interest </div> <div> </div> </div> 

… by counting from last (#inner4) because sometimes #2 isn't present …

 <div> <div> </div> <div> of interest </div> <div> </div> </div> 

and there are only 3 items (and so #inner3 becomes #inner2).

Note, #id are for clarity's sake, and not really present in my work.

I'm right now using body > .. > div:nth-child(3) but counting from top is a problem for me as explained above.

Any solution to this?

2

You should be able to grab your element with

 documentObject.lastChild.previousSibling 

where documentObject is your parent.

Edit

Thank you to David Thomas: Even more accurate would be previousElementSibling because it returns an Element and not a text node:

documentObject.lastChild.previousElementSibling 

Sources:
W3Schools
developers.mozilla

2

If I undestood you correctly you could count from the end with :nth-last-child():

. outer *:nth-last-child(2){ color: green; } 

0

The text node can be a problem in both lastChild and previousSibling This worked for me:

documentObject.lastElementChild.previousElementSibling 

Found the other part of the solution here: https://stackoverflow.com/a/18341945/8486854

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Post as a guest

Email

Required, but never shown

Pseudo-class :nth-last-child | htmlbook.

ru
Internet Explorer Chrome Opera Safari Firefox Android iOS
9.0+ 1.0+ 9.6+ 3.1+ 3.6+ 2.1+ 2.0+

Brief information

Default value No
Applicable To all elements
Specification link CSS 2 CSS 2.1 CSS 3

Psevoklass: NTH-LAST-Child is used to add styles to the elements based on the elements in the elements of the elements. Unlike the :nth-child pseudo-class, it does not count from the first element, but from the last. nine0081

Syntax

element:nth-last-child(odd | even | | ) {...}

Values ​​

odd
All odd element numbers.
even
All even element numbers.
number
The ordinal number of the child relative to its parent. The numbering starts from 1, which corresponds to the last element in the list.
expression
Specified as an+b, where a and b are integers and n is a counter that automatically takes the value 0, 1, 2...

If a is zero, then it is not written and the entry is reduced to b. If b is zero, then it is also not indicated and the expression is written in the form an. a and b can be negative numbers, in which case the plus sign is changed to minus, for example: 5n-1.

By using negative values ​​for a and b, some results can also be negative or zero. However, the elements are only affected by positive values ​​due to the fact that element numbering starts at 1.

In tab. 1 lists some possible expressions and keywords, and indicates which element numbers will be involved.

2, 5, 8, 11, 14
Tab. 1. Result for various pseudo-class values ​​
Value Element numbers Description
1 1 The last element is synonymous with the pseudo-class :last-child.
5 5 Fifth element from the end.
2n 2, 4, 6, 8, 10 All even elements, equivalent to even.
2n+1 1, 3, 5, 7, 9 All odd elements, equivalent to odd.
3N+2 -
-N+3 3, 2, 1 -
5N -2 3, 8, 13, 18, 23 -
even 2, 4, 6, 8, 10 All even elements.
odd 1, 3, 5, 7, 9 All odd elements.

Example

HTML5CSS3IECrOpSaFx

     nth-last-child    
 21342135 213621372138
Oil1634 627457
Gold469 725647
Tree773 793486
Stones2334 8853103

In this example, the :nth-last-child pseudo-class is used to highlight all odd-numbered columns, starting with the last one (Figure 1).

Fig. 1. Applying the :nth-last-child Pseudo-Class to Table Columns Useful examples

In the specification and blogs about the selector :not usually give some artificial examples, which, although they explain the syntax and principle of operation, do not carry any idea of ​​\u200b\u200bhow to benefit from the new selector.

For example:

 p:not(.classy) { color: red; } 

Well, ok, I think, in my practice there were no such situations. We got by somehow before without :not . I had to rewrite the structure of the selectors a little or reset a couple of values.

Example 1: Element without class

The :not selector can be extremely useful when we need to style user-generated content (there is no way to place classes in it), or when we have a lot of content and it is too time-consuming to place classes in it.

For example, we want to make beautiful bullets for unordered lists on the site ul li . We write the code:

 ul li { /* our pretty styles */ } 

As a result, our beautiful bullets appear not only in the content, but also, for example, in navigation, where ul li .

We are limiting the scope of the selector:

 .content ul li { /* beauty */ } 

We saved the navigation, but unnecessary bullets still pop up on sliders, news lists and other structures inside .content , which also uses ul li .

Next we have options:

1) reset interfering styles in sliders and other places. But this contradicts " DRY " and is one of the hallmarks of stinky code. In addition, it does not solve the problem once and for all: add, for example, an accordion and the lists in it will again have to be reset. nine0081

2) go the other way and put a class on all lists that need to be styled:

 .textlist li { /* beauty */ } 

This adds extra work to classify the content. Sometimes it makes sense, but no one likes extra work.

3) style only those ul li that don't have any classes at all:

 ul:not([class]) li { /* beauty */ } 

Victory! We don't need to do any extra work on arranging classes in the content. And on sliders, accordions and other structures that are not supposed to look like lists, but use them in their markup, in 99% of the cases will already have their own classes, and our styles will not affect them.

This "select only items with no class" trick is very useful for styling custom content, and can be applied to other cases than just lists.

Example 2: Changing the appearance of all elements except hover

Example

This effect can be implemented without :not by overwriting values. And it will work in more browsers. nine0081

 /* with properties overwritten */ ul: hover li { opacity:0.5; } ul:hover li:hover { opacity:1; } 

But if you have to reset too many properties, then it makes sense to use :not .

 /* using :not() */ ul:hover li:not(:hover) { opacity:0.5; } 

Example 3: Menu with separators between items

Example

As in the previous example, the desired can be achieved in several ways.

By overwriting properties. But there are two rules instead of one, what is not « DRY ".

 .menu-item:after { content: ' | '; } .menu-item:last-child:after { content: none; } 

Through :nth-last-child() . One rule, but hard to read.

 .menu-item:nth-last-child(n+2):after { content: ' | '; } 

Via :not() is the shortest and most understandable notation.

 .menu-item:not(:last-child):after { content: ' | '; } 

Example 4. Debug css

It is convenient for debugging and self-control to search/highlight pictures without alt, label without for and other errors. nine0081

 /* highlight tags without required attributes */ img:not([alt]), label:not([for]), input[type=submit]:not([value]) { outline:2px solid red; } /* alarm if the first child inside the list is not li and other similar examples */ ul > *:not(li), ol > *:not(li), dl > *:not(dt):not(dd) { outline:2px solid red; } 

Example 5: Form fields

Previously, there were not many form text fields. It was enough to write:

 select, textarea, [type="text"], [type="password"] { /* styles for text input fields */ } nine0201 

With the advent of new types of fields in HTML5, this list has grown:

 select, textarea, [type="text"], [type="password"], [type="color"], [type="date"], [type="datetime"], [type="datetime-local"], [type="email"], [type="number"], [type="search"], [type="tel"], [type="time"], [type="url"], [type="month"], [type="week"] { /* styles for text input fields */ } 

Instead of listing 14 types of inputs, 8 of them can be excluded:

 select, textarea, [type]:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not( [type="reset"]):not([type="range"]):not([type="file"]):not([type="image"]) { /* styles for text input fields */ } nine0201 

Okay, this example is not very pretty, and I still recommend the first option with enumeration, it works with IE8+, and the second option with IE9+.


Learn more