Chapter 14. Manipulating the DOM
This chapter covers
- Injecting HTML into a page
- Cloning elements
- Removing elements
- Manipulating element text
If we were to open up a JavaScript library, we’d certainly notice (most likely with some surprise) the length and complexity of the code behind simple DOM operations. Even presumably simple code, like cloning or removing a node (which both have simple DOM counterparts, like cloneNode() and removeChild()), have relatively complex implementations.
This raises two questions:
- Why is this code so complex?
- Why do I need to understand how it works if the library will take care of it for me?
The most compelling reason is performance. Understanding how DOM modification works in libraries can allow you to write better and faster code that uses the library or, alternatively, enable you to use those techniques in your own code.
There are two points that will likely be surprising to most people who are using a library: not only do libraries handle more cross-browser inconsistencies than typical handwritten code, but they frequently run faster as well. The reason for the performance improvement isn’t all that surprising—the library developers keep on top of the latest browser additions. Libraries are thus using the best-possible techniques for creating the most performant code.