如何用JavaScript在HTML中找到最后一个id

How to find last id in a HTML with JavaScript

本文关键字:最后一个 id HTML 何用 JavaScript      更新时间:2023-09-26

我有一个问题与我的javascript,我需要在我的html文档中找到一个div的最后id。我可以通过查看它来找到它,但我希望它在JavaScript中是自动的。

<body>
  <div id="start">
    <div id="1">Text</div>
    <div id="2">Text</div>
    <div id="3">Text</div>
    <div id="4">Text</div>
    <div id="5">Text</div>
    <div id="6">Text</div>
  </div>
</body>
javascript:

 function setCookie() {
    document.cookie = '1';
 }
 function startPage() {
     var cookieValueInt = parseInt(document.cookie);
     var secondPage = cookieValueInt + 1;
     document.getElementById(document.cookie).style.visibility = 'visible';
     document.getElementById(secondPage).style.visibility = 'visible';
     if (cookieValueInt == 1) {
         document.getElementById('leftarrow').style.visibility = 'hidden';
     }
 }
 function nextPage() {
     var cookieValueInt = parseInt(document.cookie);
     var secondPage = cookieValueInt + 1;
     var newCookieValue = cookieValueInt + 2;
     document.getElementById(document.cookie).style.visibility = 'hidden';
     document.getElementById(secondPage).style.visibility = 'hidden';
     document.getElementById(newCookieValue).style.visibility = 'visible';
     document.getElementById(newCookieValue + 1).style.visibility = 'visible';
     document.getElementById('leftarrow').style.visibility = 'visible';
     document.cookie = newCookieValue;

 }
 function previousPage() {
     var cookieValueInt = parseInt(document.cookie);
     var secondPage = cookieValueInt + 1;
     var newCookieValue = cookieValueInt - 2;
     document.getElementById(document.cookie).style.visibility = 'hidden';
     document.getElementById(secondPage).style.visibility = 'hidden';
     document.getElementById(newCookieValue).style.visibility = 'visible';
     document.getElementById(newCookieValue + 1).style.visibility = 'visible';
     document.cookie = newCookieValue;
     cookieValueInt = parseInt(document.cookie);
     if (cookieValueInt == 1) {
         document.getElementById('leftarrow').style.visibility = 'hidden';
     }
 }

您可以尝试使用jQuery并使用以下代码:

$(document).ready(function(){
      var attrId = $('#start').children('div:last-child').attr('id');
 });

另外,注意你的HTML是无效的,因为你缺少<</p>

请勿使用数字作为id。虽然它在HTML5中技术上是有效的,但它对id的使用很糟糕,而且很容易出现意外的重复。我建议使用<div id="someprefix_1">等等。您总是可以取ID并修剪前缀以获得号码。

除此之外,这将工作得很好(除了IE7和以下版本):

var divsWithIDs = document.querySelectorAll("div[id]"),
    lastDiv = divsWithIDs[divsWithIDs.length-1];

编辑:如果你把这个和前缀的想法结合起来,你可以很容易地得到"具有这种ID的最后一个元素":

var divsWithPrefixedIDs = document.querySelectorAll("div[id^='someprefix_']"),
    lastDiv = dovsWithPrefixedIDs[divsWithPrefixedIDs.length-1];

我建议使用容器:

var parentEl = document.getElementById("start");
var id = parentEl.children(parentEl.children.length-1).id;

另外,您不应该使用数字作为id,参见链接的答案。修改后的代码

使用getElementsByTagName并从数组中获取最后一个?

https://developer.mozilla.org/en-US/docs/DOM/element.getElementsByTagName

另外,我的建议是使用jQuery:)