Select element

3 snippets across 2 stacks - JavaScript, HTML & CSS

Also written as select elements

JSJavaScript

filter()

JS · Arrays
Syntax
arr.filter(callback(element, index, array))
Example
const products = [
  { name: "Shirt", price: 25 },
  { name: "Jacket", price: 120 },
  { name: "Cap", price: 15 },
];
const affordable = products.filter(p => p.price < 50);
console.log(affordable.map(p => p.name));
Output
["Shirt", "Cap"]

Note Returns a new array with elements that pass the test. The callback must return a truthy/falsy value.

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.

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.

Frequently asked questions

How do you select element?
This task is covered in 2 stacks on this page: JavaScript, HTML & CSS. The "filter()" snippet in JavaScript uses `arr.filter(callback(element, index, array))`.
Which code does the JavaScript example use?
The "filter()" snippet uses `arr.filter(callback(element, index, array))`, from the Arrays section of the JavaScript cheat sheet.
Which stacks cover "select element" on this page?
JavaScript, HTML & CSS. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "filter()": Returns a new array with elements that pass the test. The callback must return a truthy/falsy value.