在javascript中选择最后一个孩子

Mod*_*odS 4 javascript

我有一个无序列表的句柄(我的例子,我将调用句柄Var1),并希望能够将其最后一个li分配给一个变量.我尝试 Lastli = var1.lastChild 了我认为可行的唯一方法,但事实并非如此.我似乎无法使用Javascript而不是jQuery找到答案,任何帮助表示赞赏.

nxt*_*rld 15

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

var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;
Run Code Online (Sandbox Code Playgroud)

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

 var items = document.querySelectorAll("li");
 var lastchild = items[items.length-1];
Run Code Online (Sandbox Code Playgroud)

  • 对于任何使用 lastChild 遇到问题的人。尝试“.lastElementChild”,它会忽略可能妨碍的文本和注释节点。 (2认同)

Th0*_*ike 7

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

var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];
Run Code Online (Sandbox Code Playgroud)


aja*_*rma 5

让我们考虑一个例子

<ul >
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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