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.

Frequently asked questions

How do you get element?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Selecting Elements" snippet in JavaScript uses `document.querySelector(selector)`.
Which code does the JavaScript example use?
The "Selecting Elements" snippet uses `document.querySelector(selector)`, from the DOM Manipulation section of the JavaScript cheat sheet.
Which stacks cover "get element" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Selecting Elements": 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.