簡體   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