Hackforge Academy

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);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community