Selecting a last child in javascript

2020-02-14 05:47发布

I have a handle on an Un-ordered List (for my example i will call the handle Var1) and would like to be able to assign its last li to a variable. I tried Lastli = var1.lastChild the only method I figured would work but it didn't. I can't seem to find a answer to this using only Javascript not jQuery any help is appreciated.

标签: javascript
5条回答
2楼-- · 2020-02-14 06:19

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

var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];
查看更多
▲ chillily
3楼-- · 2020-02-14 06:23

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

查看更多
来,给爷笑一个
4楼-- · 2020-02-14 06:23

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
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-14 06:38

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

查看更多
Ridiculous、
6楼-- · 2020-02-14 06:41

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];
查看更多
登录 后发表回答