1

Both Visual Studio Code and the Mozilla Web Docs tell me that document.all is deprecated and should not be used in new websites, like mine.

However, document.all seemed to serve a very important purpose: getting a list of every node and their children in a document (either for manipulating the current HTML page, or when parsing XML file or string).

I've seen a lot of advice that suggests document.getElementById instead. But that only solves the problem of using document.all with indices to fetch one element (which is pretty obviously bad practice.) This in no way offers a solution for simply getting a list of every element and their children in a DOM, especially for iterating.

What is the proper, modern replacement for this method?

Nat Riddle
  • 928
  • 1
  • 10
  • 24
  • 4
    how about `document.querySelectorAll("*")`? – Nicholas Tower May 26 '21 at 16:35
  • 3
    `document.querySelectorAll("*")` returns exact same # of elements as `document.all` on this page. – spender May 26 '21 at 16:38
  • Thanks! I had considered this, but I suspected there may be a performance hit? – Nat Riddle May 26 '21 at 16:41
  • Why do you want to iterate all elements of your document? Use an appropriate selector for whatever you're looking. – Bergi May 26 '21 at 16:50
  • @Bergi I'm actually trying to iterate over some complicated XML from my server, which needs to be programmatically rendered to HTML. (It's a custom markup format, not exactly like HTML). I said I already recognized iterating to find just one element would be bad practice. – Nat Riddle May 26 '21 at 16:52
  • 1
    @NatRiddle But also iterating to find multiple elements would be weird. Usually you'd parse your XML using nested loops, possibly recursion, starting from the root node. – Bergi May 26 '21 at 17:00
  • @Bergi Yes, I was trying to find if there was a built-in function that recursively loops *for me*. – Nat Riddle May 26 '21 at 17:05
  • 1
    @NatRiddle The problem with not using a recursive function means that you can't really distinguish the recursive structure though – Bergi May 26 '21 at 17:11
  • @Bergi This may be true. My general idea was to use the `parentNode` property to help with that. Anyway, I'll try to get something working with your `NodeIterator`! – Nat Riddle May 26 '21 at 17:18
  • 1
    @NatRiddle There's also a `TreeWalker` you might want to look at. But recursive functions are the more natural approach to processing recursive structures imo. If you ask a new question about the actual data processing you want to do, with an example of your xml, we might be able to suggest a more concrete solution – Bergi May 26 '21 at 17:30
  • @Bergi Ahh that makes sense, thank you! Maybe I will! – Nat Riddle May 26 '21 at 17:33

2 Answers2

2

A solution for html would be document.querySelectorAll("*")

1

What is the proper, modern replacement for this method, especially for iterating?

A NodeIterator.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375