javascript 在javascript中选择最后一个孩子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13308906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:22:31  来源:igfitidea点击:

Selecting a last child in javascript

javascript

提问by ModS

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.lastChildthe 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.

我有一个无序列表的句柄(在我的例子中,我将调用句柄 Var1)并且希望能够将其最后一个 li 分配给一个变量。我尝试 Lastli = var1.lastChild了我认为可行的唯一方法,但没有。我似乎无法仅使用 Javascript 而不是 jQuery 找到答案,不胜感激。

回答by nxtwrld

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

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

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

回答by Th0rndike

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

您可以选择所有“li”并选择最后一个。就像是:

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

回答by Oriesok Vlassky

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

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

回答by Elias Van Ootegem

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

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

回答by ajay verma

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

要获取列表的最后一个子项,您只需使用 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:

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

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