Does ClassList.remove remove elements from an HTMLCollection?

I am encountering some very strange behavior with JavaScripts with the new ClassList API, let's say we have the following HTML code:

<p class="testing">Lorem Ipsum</p>
<p class="testing">Lorem Ipsum</p>

And the following JavaScript code:

var elements = document.getElementsByClassName("testing");
alert(elements.length);
elements[0].classList.remove("testing");
alert(elements.length);

The first warning will give you a value of 2, while the second warning will return 1.

It seems that removing the class from the element also removes it from the elementsHTMLCollection, which makes no sense to me at all.

You can see an example of this code HERE .

I ran into this problem when trying to remove a specific class from some elements using the following code:

var elements = document.getElementsByClassName('testing');
var elementsLength = elements.length - 1;
for(var i = 0; i <= elementsLength ; i++)
{
    elements[i].classList.remove('testing');
}

, , , , HTMLCollection, , - "TypeError: elements [i ] undefined".

, , , , / List.remove , , , List.remove. .

- ? - api classList api, ?

+4
1

, document.getElementsByClassName, , , , .

:

var elements = [].slice.call(document.getElementsByClassName('testing'));

, :

while (elements.length) elements[0].classList.remove('element-focus');
+7

Source: https://habr.com/ru/post/1529503/


All Articles