Selecting Elements

What is the DOM?

The DOM (Document Object Model) is the browser's live, tree-shaped representation of the page. Every element is an object JavaScript can read and change; changes appear on screen immediately.

MethodReturns
document.getElementById("id")one element or null
document.querySelector(".card p")the first element matching a CSS selector
document.querySelectorAll("li")a NodeList of all matches
element.closest(".card")nearest ancestor (or itself) matching

Example

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<ul id="list"><li>HTML</li><li class="hot">CSS</li><li>JS</li></ul>
<p id="out"></p>
<script>
  const items = document.querySelectorAll("#list li");
  const hot = document.querySelector(".hot");
  hot.style.color = "crimson";
  document.getElementById("out").textContent = items.length + " items, hot one: " + hot.textContent;
</script>

</body>
</html>

Result