HAP looking confused while studying a map

CSS Selectors and DOM Reading Methods

📋 Cheat Sheet

Everything I keep forgetting about selectors and reading methods, all in one place. I made this so I'd stop looking things up every five minutes. 🟠

CSS Selector Syntax

These are the same selectors from CSS stylesheets — querySelector uses identical syntax.

.class

Selects by class name. Example: querySelector('.card-header') finds the first element with class card-header.

#id

Selects by ID. Example: querySelector('#robot-name') finds the element with ID robot-name.

tag

Selects by tag name. Example: querySelector('h2') finds the first <h2> element.

parent child

Descendant selector. Example: querySelector('.card-header h2') finds an <h2> anywhere inside .card-header.

parent > child

Direct child selector. Example: querySelector('.card-header > h2') finds an <h2> that is a direct child of .card-header.

[attr]

Attribute selector. Example: querySelector('[data-status]') finds the first element with a data-status attribute.

[attr="val"]

Attribute value selector. Example: querySelector('[data-status="online"]') finds elements where data-status equals "online".

querySelector vs querySelectorAll

querySelector — first match only:
const header = document.querySelector('.card-header');
// Returns: one Element, or null if nothing matches
querySelectorAll — all matches:
const rows = document.querySelectorAll('.info-row');
// Returns: a NodeList of all matching elements (can be empty)
// Loop with forEach:
rows.forEach(row => console.log(row.textContent));

Reading Methods Comparison

Three ways to read from the same element — three different results.

textContent

Returns: Plain text
Hidden elements: Included
HTML tags: Stripped
Performance: Fast
Best for: Reading text safely. The recommended default.

innerText

Returns: Visible text only
Hidden elements: Excluded
HTML tags: Stripped
Performance: Slower (checks layout)
Best for: When visibility matters — reading what the user actually sees.

innerHTML

Returns: HTML markup as a string
Hidden elements: Included
HTML tags: Preserved
Performance: Fast
Best for: Reading HTML structure. Dangerous when used for writing.

getAttribute()

Reading attributes from elements:
const el = document.querySelector('#status-message');

el.getAttribute('data-status');  // "online"
el.getAttribute('id');           // "status-message"
el.getAttribute('class');        // "status active" (full string, NOT an array)

Remember: getAttribute('class') returns one space-separated string, even when there are multiple classes.

🟠 Back to the Station:

This cheat sheet goes with Station 3: Reading the Room. Head back there for the full story of how I learned all this — including Grace's warning about innerHTML.