AV's Blog

Review of Basic DOM Manipulations

October 10, 2018

Just putting some notes on some practices on DOM manipulation. This involves using the browser developer tools. In the case of Chrome, it can be accessed using Cmd + Option + i on OSX.

First up, in the Elements tab, one can use the DOM viewer or element selector tool which allows navigation through the DOM and selection of individual elements. Shortcut for this is Cmd + Shift + C on OSX.

On the Console tab, one can execute JavaScript codes. Typing in window will give the window object. To clear the console, use the clear icon.

To query the DOM, common methods include:

  • document.getElementById
  • document.getElementsByClassName
  • document.getElementsByTagName

The last two methods will give a collection of elements.

Query selector methods:

  • document.querySelector
  • document.querySelectorAll

The collection returned by these methods are not arrays. But one can use Array.prototype.slice.call or Array.from to convert them to array-like objects.

const ps = document.getElementsByTagName('p')
Array.from(ps).forEach(p => (p.style.backgroundColor = 'red')) // turns all p's red

Remember: Use console.dir when needed.