Finding HTML Elements
The Document Object Model (DOM) represents your HTML as JavaScript objects.
You can select and manipulate HTML elements using JavaScript.
// Select by ID
const element = document.getElementById('myId');
// Select by Class Name
const elements = document.getElementsByClassName('myClass');
// Returns HTMLCollection (array-like)
// Select by Tag Name
const paragraphs = document.getElementsByTagName('p');
// Query Selector (CSS selector)
const first = document.querySelector('.myClass');
const all = document.querySelectorAll('.myClass');
// Returns first match / NodeList of all matches
// Complex Selectors
document.querySelector('#container .item:first-child');
document.querySelectorAll('div.card[data-active="true"]');
// Parent/Child Navigation
element.parentElement; // Parent
element.children; // Children
element.firstElementChild; // First child
element.lastElementChild; // Last child
element.nextElementSibling; // Next sibling
element.previousElementSibling; // Previous sibling
- getElementById() - Select by ID
- getElementsByClassName() - Select by class
- getElementsByTagName() - Select by tag
- querySelector() - Select first match (CSS)
- querySelectorAll() - Select all matches
- querySelector is most versatile
- Returns null if not found
Try DOM Selection
<div class="dom-demo">
<h3>Element Selector</h3>
<div id="container">
<p class="text" data-type="intro">First paragraph</p>
<p class="text" data-type="content">Second paragraph</p>
<p class="text highlight" data-type="content">Third paragraph (highlighted)</p>
</div>
<button onclick="selectById()">Select by ID</button>
<button onclick="selectByClass()">Select by Class</button>
<button onclick="selectHighlight()">Select Highlighted</button>
<div id="selectionOutput"></div>
</div>
Note: querySelector and querySelectorAll are the most flexible. Use them for most selections!