Category: javascript
QuerySelector in javascript
Published on 09 Mar 2026
Explanation
Select the first element that matches a
CSS selector.
Commonly used to select elements
by class.
Code:
const ele = document.querySelector('.box');
console.log(element);
Explanation
Select an element using its ID.
Similar to getElementById
but uses CSS selector syntax.
Code:
const ele = document.querySelector('#title');
console.log(ele.textContent);
Explanation
Select an element by tag name.
the first matching tag in the document.
Code:
const ele = document.querySelector('p');
console.log(ele.innerText);
Explanation
Select a nested element using a descendant
selector.
Code:
const ele = document.querySelector('.menu li');
console.log(ele);
Explanation
Modify the style of the selected element.
Add an event listener to the selected
element.
Code:
const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';
const button = document.querySelector('#btn');
button.addEventListener('click', () => {
alert('Button clicked');
});
Explanation
Change the text content of the selected
element.
Select an input field and read its
value.
Code:
const title = document.querySelector('.title');
title.textContent = 'Welcome to JavaScript';
const input = document.querySelector('#username');
console.log(input.value);
Explanation
Select an element with multiple class conditions.
Select a checked checkbox or radio button.
Code:
const specialItem = document.querySelector('.card.active');
console.log(specialItem);
const checkedOption = document.querySelector('input[type="radio"]:checked');
console.log(checkedOption.value);