</> Code Corner

JavaScript · JS HTML DOM · Lesson 47

DOM Methods & Elements

Find elements by id, tag, class and CSS selector.

To manipulate HTML elements, you first have to find them.

Example

<p id="intro">Intro paragraph</p>
<p class="note">Note one</p>
<p class="note">Note two</p>
<p id="demo"></p>
<script>
const intro = document.getElementById("intro");
const notes = document.getElementsByClassName("note");
const paragraphs = document.getElementsByTagName("p");
const firstNote = document.querySelector("p.note");
const allNotes = document.querySelectorAll("p.note");
document.getElementById("demo").innerHTML =
  intro.innerHTML + " | " + notes.length + " notes | " + paragraphs.length + " paragraphs | first: " +
  firstNote.textContent + " | querySelectorAll: " + allNotes.length;
</script>
Method Finds
getElementById(id) One element by id
getElementsByTagName(name) Elements by tag name
getElementsByClassName(name) Elements by class
querySelector(css) The first element matching a CSS selector
querySelectorAll(css) All elements matching a CSS selector

Keep reading “DOM Methods & Elements”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋