Use universal selector to get all DOM nodes in vanilla Javascript

The universal selector (*), matches the name of any element type. It matches any single element in the document tree. Some ways it can be used:

  1. document.querySelectorAll("*") – to get all elements.
  2. document.querySelectorAll("body *") – to get all descendant elements of body element.

Example – use universal selector to get all DOM nodes

function printAllNodes() {
  var elementList = document.querySelectorAll("*");
  for (i = 0; i < elementList.length; ++i) {
    document.querySelector("pre").innerText += elementList[i].nodeName + "\n";
window.addEventListener('load', printAllNodes);


Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments