我有一个
我尝试了以下操作:
然而,它似乎不起作用。
我想使用原生JS来完成这个任务,不使用jQuery。
<ol>
(保存在Var1
中),希望能够将它的最后一个<li>
元素赋值给一个变量。我尝试了以下操作:
Lastli = var1.lastChild
然而,它似乎不起作用。
我想使用原生JS来完成这个任务,不使用jQuery。
<ol>
(保存在Var1
中),希望能够将它的最后一个<li>
元素赋值给一个变量。Lastli = var1.lastChild
var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;
或者您可以将所有项目选择为数组并获取最后一个项目。以下是一个快速示例:
var items = document.querySelectorAll("li");
var lastchild = items[items.length-1];
document.querySelector("li:last-child")
。 - Muhammad.lastElementChild
,它会忽略文本和注释节点,这可能会妨碍你的操作。 - di3var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];
<ul >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
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
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
.childNodes[childNodes.length - 1]
。可以使用 ulReference.children[ulReference.children.length -1]
或者 ulReference.childNodes[ulReference.childNodes.length -1]
。两者之间的区别可以在 这里 找到。
最简单的方法是使用 document.querySelector
并使用 :last-child
来获取它。
例如:
const list = document.querySelector("li:last-child");
<li>
的原因可能是在其结束的</li>
标签后面有一些空格。如果省略闭合标签,你可以通过ul.lastChild
访问它;) - J. K.::var x = document.getElementsByClassName('listSection')[0].getElementsByTagName('ul')[0]; var2 = x.lastChild; console.log(var2);
- ModS