Choosing the last child in javascript

I have an unordered list descriptor (for my example, I will call the Var1 descriptor) and would like to be able to assign its last li to a variable. I tried Lastli = var1.lastChild only method that I thought would work, but it is not. I can not find the answer to this using only Javascript and not jQuery. Any help is appreciated.

+4
source share
5 answers

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 elements in the array and get the last element. Here is a quick example:

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

you can select all "li" and take the last one. Sort of:

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

Try the following: .childNodes[childNodes.length - 1]

+2
source

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

+1
source

Let's look at an example

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

To get the last child of a list, you can simply use 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 need the nth child element for which 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 items in this list:

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

Source: https://habr.com/ru/post/1445055/


All Articles