❮ Previous ❮ Element Object Reference Next ❯
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.
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.
lastChild
returns the list child node: An element node, a text node, or a comment node.
Whitespace between elements are also text nodes.
The lastElementChild Property
The lastElementChild
property returns the last child element (ignores text and comment nodes).
The childNodes Property
The firstChild Property
The nextSibling Property
The previousSibling Property
The parentNode Property
The nodeName Property
The nodeType Property
The nodeValue Property
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 returns child nodes (element nodes, text nodes, and comment nodes).
children returns child elements (not text and comment nodes).
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 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).
element.lastChild
or
node.lastChild
Type | Description |
Node | The last child of a node.null if no child exists. |
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 »
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 ❯
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.
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
.
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 using Google
Sign up using Facebook
Sign up using Email and Password
Required, but never shown
Required, but never shown
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS |
9.0+ | 1.0+ | 9.6+ | 3.1+ | 3.6+ | 2.1+ | 2.0+ |
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
element:nth-last-child(odd | even |
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.
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 | 2, 5, 8, 11, 14- | |
-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
2134 2135 2136 2137 2138 Oil 16 34 62 74 57 Gold 4 69 72 56 47 Tree 7 73 79 34 86 Stones 23 34 88 53 103
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.
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
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
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: ' | '; }
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; }
Previously, there were not many form text fields. It was enough to write:
select, textarea, [type="text"], [type="password"] { /* styles for text input fields */ } nine0201With 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 */ } nine0201Okay, 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+.