ModS
ModS

Reputation: 846

Selecting the last child of an element in JavaScript

I have an <ol> (saved to Var1) and would like to be able to assign its last <li> element to a variable.

I tried doing the following:

Lastli = var1.lastChild

However, it doesn't seem to work.

I'd like to do this with vanilla JS, and no jQuery.

Upvotes: 9

Views: 39392

Answers (6)

nxtwrld
nxtwrld

Reputation: 2062

You can select the parent element and use the lastChild property.

var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;

Or you select all the items into an array and get the last item. Here is a quick example:

var items = document.querySelectorAll("li");
var lastchild = items[items.length-1];

Upvotes: 29

Pedro Elton
Pedro Elton

Reputation: 36

The simplest way is to use the document.querySelector and use the :last-child to get it.

Exemple:

const list = document.querySelector("li:last-child");

Upvotes: 0

ajay verma
ajay verma

Reputation: 359

Lets consider an example

<ul >
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

To get the last child of the list you can simply make use of queryselector

document.querySelector('li:last-child'); //this will return Milk which is the last child of the list
document.querySelector('li:first-child') OR document.querySelector('li'); //both will give you the first child of the list

Suppose you want the n-th child for that you can use the following syntax:

document.querySelector('li:nth-child(2)');  //it will return the second child (here Tea)

If you want all the list item in the given list:

document.getElementsByTagName('li') //(Will return the whole list)here i am using tagname. It can be also applied on classname or element id

Upvotes: 5

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

either ulReference.children[ulReference.children.length -1] or ulReference.childNodes[ulReference.childNodes.length -1]. The difference between the two can be found here

Upvotes: 1

Th0rndike
Th0rndike

Reputation: 3436

you can select all 'li' and take the last one. Something like:

var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];

Upvotes: 8

Oriesok Vlassky
Oriesok Vlassky

Reputation: 797

Try this: .childNodes[childNodes.length - 1]

Upvotes: 2

Related Questions