Get All Elements By ClassName and Change ClassName

前端 未结 5 2086
深忆病人
深忆病人 2020-11-29 08:59

I would like to...

  1. Scan the document for all elements that have a certain class name
  2. Perform some key functions on the innerHTML of that element
5条回答
  •  春和景丽
    2020-11-29 09:41

    Most DOM functions that return a list of elements, return a NodeList rather than an array. The biggest difference is that a NodeList is typically live, meaning that changing the document can cause nodes to magically appear or disappear. That can cause nodes to move around a bit, and throw off a loop that doesn't account for it.

    Rather than turning the list into an array or whatever, though, you could simply loop backwards on the list you get back.

    function example()
    {
        var elements = document.getElementsByClassName("exampleClass");
    
        for(var i = elements.length - 1; i >= 0; --i)
        {
            // PERFORM STUFF ON THE ELEMENT
            elements[i].className = "exampleClassComplete";
    
            // elements[i] no longer exists past this point, in most browsers
        }   
    }
    

    The liveness of a NodeList won't matter at that point, since the only elements removed from it will be the ones after the one you're currently on. The nodes that appear before it won't be affected.

提交回复
热议问题