Get element

2 snippets across 2 stacks — JavaScript, Python

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.

PYPython

Indexing & Negative Indexing

PY · Lists
syntax
items[index]
items[-index]
example
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
output
apple
date
cherry

Note Index 0 is the first element, -1 is the last. Accessing an index beyond the list length raises IndexError.