- Part 1: Creating and Using Variables
- Part 2: Data Types and Arrays
- Part 3: Functions
- Part 4: Objects
- Part 5: Document Object Model
- Part 6: Conditional Statements
- Part 7: Loops
Document Object Model
In the document object model (DOM), individual elements within a HTML document can be accessed through a root object called document.
As was introduced in a previous section, this variable document is in the global scope. It can be access inside of any function and used to access, search for, or change the object representing the HTML.
Accessing Elements within DOM
The DOM follows a metaphor of parents and children. Any elements found within an elements are their children and can be accessed, using the DOM, by using its children property.
In fact, the results returned from the children property of objects in DOM acts like (but is not quite) an array. It has a length and can be accessed through an index.
All HTML elements represented as objects within the DOM also have two properties commonly used to check their contents: innerText and innerHTML.
innerText Property of HTML Elements
The innerText property of an HTML element is set to its text contents and that of any children it has.
Changing its value only changes the text content of an element.
innerHTML Property of HTML Elements
The innerHTML property of an HTML element is set to its HTML and that of any children it has.
Changing its value changes the HTML content of an element.
Searching for Elements within DOM
Because searching across elements using their children could become tedious, the DOM also provides some high-level searching functions that can return groups or individual elements.
- getElementById: Search for an element based on its ID attribute
- getElementsByClassName: Search for element(s) based on their CLASS attribute
- getElementsByTagName: Search for element(s) based on their tag name
Changing Elements in DOM
As was mentioned in the parts on innerText and innerHTML, changing these properties changes the document itself. The DOM is not merely a representation of the document; it is the document. Making any changes affects the HTML document as the user sees it.
For example, setting the innerHTML of an element to an empty string will erase its children. The new HTML content of the element will be the empty string itself and all other content will be removed. (It will be restored when the document is reloaded.)