Chapter 12. Working the DOM
This chapter covers
- Inserting HTML into the DOM
- Understanding DOM attributes and DOM properties
- Discovering computed styles
- Dealing with layout thrashing
Up to now, you’ve been learning mostly about JavaScript the language, and although there are plenty of nuances to pure JavaScript, developing web applications definitely doesn’t get any easier when we throw the browser’s Document Object Model (DOM) into the mix. One of the primary means for achieving highly dynamic web applications that respond to user actions is by modifying the DOM. But if we were to open up a JavaScript library, you’d notice the length and complexity of the code behind simple DOM operations. Even presumably simple operations like cloneNode and removeChild have relatively complex implementations.
This raises two questions:
- Why is this code so complex?
- Why do you need to understand how it works if the library will take care of it for you?
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.
So we’ll start this chapter by seeing how to create new parts of our pages, on demand, by injecting arbitrary HTML. We’ll continue by examining all the conundrums that browsers throw at us with respect to element properties and attributes, and we’ll discover why the results aren’t always exactly what we might expect.