按类名获取所有元素并更改ClassName [英] Get All Elements By ClassName and Change ClassName

查看:146
本文介绍了按类名获取所有元素并更改ClassName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想...


  1. 扫描文档以查找具有特定班级名称的所有元素

  2. 在该元素的innerHTML上执行一些关键函数

  3. 更改该元素的类名,这样如果我稍后再进行一次扫描,则不会重做该元素

我认为这段代码可以工作但是由于某种原因它会在第一个实例之后中断循环并且元素的类名永远不会改变。没有框架请。

I thought this code would work but for some reason it breaks the loop after the first instance and the element's class names are never changed. No frameworks please.

function example()
{
    var elementArray;

    elementArray = document.getElementsByClassName("exampleClass");

    for(var i = 0; i < elementArray.length; i++)
    {
        // PERFORM STUFF ON THE ELEMENT
        elementArray[i].setAttribute("class", "exampleClassComplete");
        alert(elementArray[i].className);
    }   
}

编辑(最终答案) - 这是最终产品以及我如何在我的网站中实施@ cHao的解决方案。目标是在页面上抓取各种时间戳并将其更改为时间。谢谢大家的帮助,我从这个问题中学到了很多。

EDIT (FINAL ANSWER) -- Here is the final product and how I have implemented @cHao's solution within my site. The objective was to grab an assortment of timestamps on the page and change them to time ago. Thank you all for your help, I learned a ton from this question.

function setAllTimeAgos()
{
    var timestampArray = document.getElementsByClassName("timeAgo");

    for(var i = (timestampArray.length - 1); i >= 0; i--)
    {
        timestampArray[i].innerHTML = getTimeAgo(timestampArray[i].innerHTML);
        timestampArray[i].className = "timeAgoComplete";
    }
}


推荐答案

问题是返回给你的NodeList是实时 - 它会随着你改变类名而改变。也就是说,当您更改第一个元素上的类时,列表会立即缩短一个元素。

The problem is that the NodeList returned to you is "live" - it changes as you alter the class name. That is, when you change the class on the first element, the list is immediately one element shorter than it was.

试试这个:

  while (elementArray.length) {
    elementArray[0].className = "exampleClassComplete";
  }

(不需要使用 setAttribute()设置class值 - 只需更新className属性。在旧版本的IE中使用 setAttribute()无论如何都无法正常工作。 )

(There's no need to use setAttribute() to set the "class" value - just update the "className" property. Using setAttribute() in old versions of IE wouldn't work anyway.)

或者,将NodeList转换为普通数组,然后使用索引迭代:

Alternatively, convert your NodeList to a plain array, and then use your indexed iteration:

  elementArray = [].slice.call(elementArray, 0);
  for (var i = 0; i < elementArray.length; ++i)
    elementArray[i].className = "whatever";

正如评论中所指出的,这样做的好处是不依赖关于NodeList对象的语义。 (另请注意,再次感谢评论,如果您需要在旧版本的Internet Explorer中使用它,则必须编写显式循环以将NodeList中的元素引用复制到数组。)

As pointed out in a comment, this has the advantage of not relying on the semantics of NodeList objects. (Note also, thanks again to a comment, that if you need this to work in older versions of Internet Explorer, you'd have to write an explicit loop to copy element references from the NodeList to an array.)

这篇关于按类名获取所有元素并更改ClassName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆