cookbook home ~ main site ~ links ~ podcast ~ mastodon

Get All Document Elements With IDs

This is an experiment in automatically creating an object that contains every element on a page that has the ID. It uses a treewalker to find elements with IDs and adds them to the object using the ID as the key.

The idea is to make a vanilla approach simpler because you won't have to load elements independently.

HTML

<p id="alfa"></p>
<p id="bravo"></p>

JavaScript

const els = {}

const loadElements = () => {
  const treeWalker = document.createTreeWalker(document.body)

  let currentNode = treeWalker.currentNode
  while (currentNode) {
    if (currentNode.id !== undefined && currentNode.id !== '') {
      els[currentNode.id] = currentNode
    }
    currentNode = treeWalker.nextNode()
  }
}

const updateValues = () => {
  els.alfa.innerHTML = 'alfa has been updated'
  els.bravo.innerHTML = 'bravo has been updated'
}

const init = () => {
  loadElements()
  updateValues()
}

document.addEventListener('DOMContentLoaded', init)

EXAMPLE

References