Css selector

2 snippets across 2 stacks — HTML & CSS, JavaScript

Also written as CSS selector

HCHTML & CSS

Element, Class & ID Selectors

HC · CSS Selectors
syntax
element { }
.class { }
#id { }
example
p {
  line-height: 1.6;
}

.alert {
  padding: 12px 16px;
  border-radius: 6px;
}

#main-header {
  position: sticky;
  top: 0;
}

Note Prefer classes over IDs for styling since IDs have much higher specificity and cannot be reused. IDs are fine for JavaScript hooks and anchor targets.

JSJavaScript

Selecting Elements

JS · DOM Manipulation
syntax
document.querySelector(selector)
document.querySelectorAll(selector)
document.getElementById(id)
example
const header = document.querySelector("h1");
const buttons = document.querySelectorAll(".btn");
const main = document.getElementById("main-content");

// querySelectorAll returns a static NodeList
buttons.forEach(btn => {
  console.log(btn.textContent);
});

Note querySelector returns the first match or null. querySelectorAll returns a static NodeList (does not auto-update). Use Array.from() if you need full array methods.