繁体   English   中英

选择 javascript 中的最后一个孩子

[英]Selecting a last child in javascript

我有一个无序列表的句柄(对于我的示例,我将调用句柄 Var1)并希望能够将其最后一个 li 分配给一个变量。 我尝试Lastli = var1.lastChild ,这是我认为唯一可行的方法,但没有成功。 我似乎无法仅使用 Javascript 而不是 jQuery 找到答案,感谢您的帮助。

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

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

或者您将所有项目选择到一个数组中并获取最后一项。 这是一个简单的例子:

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

你可以选择所有'li'并选择最后一个。 就像是:

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

试试这个: .childNodes[childNodes.length - 1]

ulReference.children[ulReference.children.length -1]ulReference.childNodes[ulReference.childNodes.length -1] 这两者之间的区别可以在这里找到

让我们考虑一个例子

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

要获取列表的最后一个子项,您可以简单地使用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

假设你想要第n个孩子,你可以使用以下语法:

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

如果您想要给定列表中的所有列表项:

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

最简单的方法是使用document.querySelector并使用:last-child来获取它。

例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM