在JavaScript中选择一个元素的最后一个子元素

7
我有一个<ol>(保存在Var1中),希望能够将它的最后一个<li>元素赋值给一个变量。
我尝试了以下操作:
Lastli = var1.lastChild

然而,它似乎不起作用。
我想使用原生JS来完成这个任务,不使用jQuery。

2
请提供一些最少的代码。 - willome
1
你无法获取最后一个<li>的原因可能是在其结束的</li>标签后面有一些空格。如果省略闭合标签,你可以通过ul.lastChild访问它;) - J. K.
谢谢大家!我忘记把它定义为第一个ul,即使它是唯一的Ul。::var x = document.getElementsByClassName('listSection')[0].getElementsByTagName('ul')[0]; var2 = x.lastChild; console.log(var2); - ModS
6个回答

26
您可以选择父元素并使用lastChild属性。
var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;

或者您可以将所有项目选择为数组并获取最后一个项目。以下是一个快速示例:

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

1
不需要为querySelector选择所有项,只需使用document.querySelector("li:last-child") - Muhammad
2
对于使用 lastChild 函数出现问题的人,请尝试使用 .lastElementChild,它会忽略文本和注释节点,这可能会妨碍你的操作。 - di3

8
你可以选择所有的 'li' 并取最后一个。类似这样:
var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];

5
让我们考虑一个例子。
<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

2
尝试一下:.childNodes[childNodes.length - 1]

1

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


0

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

例如:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接