Search code examples
javascriptgetelementsbytagname

Can I blindly replace all occurrences of document.all in my entire project with document.getElementsByTagName('*')?


I'm working on a lot of legacy code and have a huge number of instances of document.all usage. I need to replace all these instances (in bulk) with something Microsoft supports (as I understand document.all is not supported anymore).

Is it a safe option to replace all the instances of document.all with document.getElementsByTagName()? Please bear in mind that document.all could come in many flavours like document.all.item("") etc.. I need to know if document.getElementsByTag('') would work as a solution for blind replacement of document.all wherever it is used (in whatever form)


Solution

  • From the MDN page about #document

    document.all
    Provides access to all elements with an id. This is a legacy, non-standard, interface and you should use the document.getElementById() method instead.

    Therefore, no document.getElementsByTagName("*") will return more elements than just elements with an id

    This definition means you could do

    document.querySelectorAll('[id]'); // NodeList
    

    However

    MSDN has a different definition

    The all collection includes one element object for each valid HTML tag. If a valid tag has a matching end tag, both tags are represented by the same element object.

    In this case it is true that document.getElementsByTagName("*") gives a similar result (HTMLCollection)

    However, again

    The NodeList will fail to reproduce the expected result of document.all.id_value, document.all[id_value] or document.all(foo).

    The HTMLCollection does support document.all.id_value and document.all[id_value] as described in w3's DOM spec, though I strongly recommend against use of this over other methods such as getElementById

    Really, you're going to have to go through the code quickly to make sure it will work as expected with whichever alternative you choose.