在JavaScript中选择最后一个孩子 [英] Selecting a last child in javascript

查看:43
本文介绍了在JavaScript中选择最后一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在无序列表上有一个句柄(例如,我将其称为Var1句柄),并且希望能够将其最后一个li分配给变量.我尝试了 Lastli = var1.lastChild ,这是我认为唯一可行的方法,但没有奏效.我似乎无法仅使用Javascript而不是jQuery来找到答案,感谢任何帮助.

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.

推荐答案

您可以选择父元素并使用lastChild属性.

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];

这篇关于在JavaScript中选择最后一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆