简单的 dom 类选择器

发布于 2024-10-16 14:38:27 字数 1165 浏览 9 评论 0原文

<ul>
  <li> <div class="time"> at 2011-02-05 17:44:28</div></li>
  <li> <div class="time"> at 2011-02-05 17:40:20</div></li>
  <li> <div class="time"> at 2011-02-05 17:15:11</div></li>
  <li> <div class="time"> at 2011-02-05 17:04:14</div></li>
  <li> <div class="time"> at 2011-02-05 15:54:56</div></li>
</ul>

//Reformat timeStamps
var timeIndex = 0;
while (timeIndex < 51)
{
  var timeIndexHTML = document.getElementsByClassName("time")[timeIndex].innerHTML;
  timeIndexHTML = "Reformatted time";
  document.getElementsByClassName("time")[timeIndex].innerHTML = timeIndexHTML;
  timeIndex++;
}

如何检测类的最后一个元素,然后将 51 设为变量?

//
//*****************************EDITS HERE**************************************
//
//Example:
  var LAST_ELEMENT_OF_CLASS = someMagicCode("time");

然后

while (timeIndex < LAST_ELEMENT_OF_CLASS +1){...}

注意它目前不起作用,因为它尝试评估

document.getElementsByClassName("time")[5]

哪个不存在

<ul>
  <li> <div class="time"> at 2011-02-05 17:44:28</div></li>
  <li> <div class="time"> at 2011-02-05 17:40:20</div></li>
  <li> <div class="time"> at 2011-02-05 17:15:11</div></li>
  <li> <div class="time"> at 2011-02-05 17:04:14</div></li>
  <li> <div class="time"> at 2011-02-05 15:54:56</div></li>
</ul>

//Reformat timeStamps
var timeIndex = 0;
while (timeIndex < 51)
{
  var timeIndexHTML = document.getElementsByClassName("time")[timeIndex].innerHTML;
  timeIndexHTML = "Reformatted time";
  document.getElementsByClassName("time")[timeIndex].innerHTML = timeIndexHTML;
  timeIndex++;
}

How can I detect the last element of a class, and then make 51 a variable?

//
//*****************************EDITS HERE**************************************
//
//Example:
  var LAST_ELEMENT_OF_CLASS = someMagicCode("time");

and then

while (timeIndex < LAST_ELEMENT_OF_CLASS +1){...}

Note it currently doesn't work because it tries to evaluate

document.getElementsByClassName("time")[5]

Which doesn't exist

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小猫一只 2024-10-23 14:38:27

让我猜一下。你想要的是这样的:(

var elems = document.getElementsByClassName("time");
for(var timeIndex = 0; timeIndex < elems.length; ++timeIndex)
{
  elems[timeIndex].innerHTML = "Reformatted time";
}

如果这不是你想要的,请澄清问题)

Let me guess. What you want is this:

var elems = document.getElementsByClassName("time");
for(var timeIndex = 0; timeIndex < elems.length; ++timeIndex)
{
  elems[timeIndex].innerHTML = "Reformatted time";
}

(if that's not what you want please clarify question)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文