Reading the DOM

Javascript has built-in APIs to read the current state of the DOM.

The document var

document is a special variable inside the browser. It is the starting point for anything to do with the DOM

Each element in the dom is of the type: HTMLElement.

document.querySelector(string)

  • string is a css selector string:
  • returns HTMLElement: The first HTML element that matches the css selector from the DOM

If the DOM has the following HTML:

<div>
  <p>a</p>
  <p class="red">b</p>
  <p>c</p>
</div>
document.querySelector('p') // find the first p tag

// => <p>a</p> <- the first p tag!
document.querySelector('.red') // find the first p tag

// => <p class="red">b</p>
document.querySelectorAll('#c') // find the first p tag with id="c"

// => [<p id="c">c</p>]
document.querySelector('div') // find the first div tag

// => <div>
//      <p>a</p>
//      <p class="red">b</p>
//      <p>c</p>
//    </div>

document.querySelectorAll(string)

  • string is a css selector string:
  • returns an array of HTMLElement: All the HTML elements that match the css selector from the DOM

If the DOM has the following HTML:

<div>
  <p>a</p>
  <p class="red">b</p>
  <p id="c">c</p>
</div>
document.querySelectorAll('p')

// => [<p>a</p>, <p class="red">b</p>, <p>c</p>]
document.querySelectorAll('.red') // find the p tags with class="red"

// => [<p class="red">b</p>]
document.querySelectorAll('#c') // find the p tags with id="c"

// => [<p id="c">c</p>]
document.querySelectorAll('div') // find the div tags

// => [<div>
//      <p>a</p>
//      <p class="red">b</p>
//      <p>c</p>
//    </div>]

htmlElement.className

HTMLElement has a key className which is the right hand side of it's class= attribute.

If the DOM has the following HTML:

<p class="red">b</p>
const htmlElement = document.querySelector('p') // a HTMLElement: <p class="red">b</p>
htmlElement.className

// => "red"

htmlElement.textContent

HTMLElement has a key textContent which is the text between the tags.

If the DOM has the following HTML:

<p class="red">b</p>
const htmlElement = document.querySelector('p') // a HTMLElement: <p class="red">b</p>
htmlElement.textContent

// => "b"