• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Unexpected behavior while iterating over JavaScript DOMTokenList

Resolved: Unexpected behavior while iterating over JavaScript DOMTokenList

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I don’t quite get how iteration over a JavaScript DOMTokenList works. I guess, this is not specific for a DOMTokenList but rather for (many?) JavaScript-Objects. As you can see in the below snippet, I want to remve all classes of a div by iterating over the corresponding DOMTokenList. But only function testC() which first collects the class names in an extra array removes all classes. Functions testA() and testB() will alwyas retain the css class b. Why?
Remarks: I know of course that it’s possible to remove all classes of an object in a better way. However, I stumbled over this for me unexpected behavior and want to understand what I did wrong.


Answer:

This is happening because you are altering the list during the loop. By altering the list you shift the indexes. Lets go over the loop in more detail:
First iteration:
  • Current index: 0
  • Index of a: 0 (matches current index)
  • Index of b: 1
  • Index of c: 2

Second iteration:
  • Current index: 1
  • Index of a: removed
  • Index of b: 0
  • Index of c: 1 (matches current index)

Last iteration:
  • Current index: 2
  • Index of a: removed
  • Index of b: 0
  • Index of c: removed

As you can see the only items that get removed are the ones where the current index matches the elements index.
To solve this issue you can make a copy of the classList and loop over it.


If you have better answer, please add a comment about this, thank you!

dom html javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Shopware 400 Status Error “This value is too long. It should have 255 character or less.” When I Try Updating Database Table

01/04/2023

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.