Playing with the DOM is all about adding interactivity to your page. The DOM (Document Object Model) is the interface between your JavaScript and your HTML+CSS. The browser takes all the elements of your page and turns it into a JavaScript object.

All the elements of the DOM for your page are contained in the object “document”. You can show everything in “document” by using this command in your browser’s console:

console.dir(document);

Working with the DOM is similar to CSS. This is because you select an element then you manipulate it. Here’s an example of what I mean:

var batmanComments = document.querySelectorAll( ".batmanComments" );

In the above example, we are selecting all elements with the class “batmanComments”. Now to do something with our newly selected elements:

var length = batmanComments.length;
for (var i = 0; i < length; i++) {
    batmanComments[i].textContent = “Ironman sucks”
}

This code replaces the contents of each element in the “batmanComments” array with the string “Ironman sucks”… because maturity isn’t Batman’s strength.

If you want more details on working with the DOM, MDN is a good place to start and an even better reference as you’re learning.


Posted

in

by