Chapter 12. Working with HTML
In 1995 Netscape tasked software developer Brendan Eich with creating a programming language designed to add interactivity to pages in the Netscape Navigator browser. In response, Eich infamously developed the first version of JavaScript in 10 days. A few years later, JavaScript became a cross-browser standard through the adoption of the ECMAScript standardization.
Despite the early attempt at standardization, web developers battled for years with browsers that had different JavaScript engine interpretations or features. Popular libraries, such as jQuery, effectively allowed us to write simple cross-browser JavaScript. Thankfully, today’s browsers share a near uniform implementation of the language, allowing web developers to write “vanilla” (library-free) JavaScript to interact with an HTML page.
When working with HTML, we are working with the Document Object Model (DOM), which is the data representation of the HTML page. The recipes in this chapter will review how to interact with the DOM of an HTML page by selecting, updating, and removing elements from the page.
Accessing a Given Element and Finding Its Parent and Child Elements
Problem
You want to access a specific web page element, and then find its parent and child elements.
Solution
Give the element a unique identifier:
<divid="demodiv"><p>This is text.</p></div>
Use document.getElementById() to get a reference to the specific element:
constdemodiv=document.getElementById("demodiv" ...