Hackforge Academy

Category: javascript

dom selecting elements getelementbyid queryselector

Published on 30 Sep 2026

Explanation

getElementById() selects an HTML element using its unique id attribute.

Code:

const title = document.getElementById('title');

console.log(title);

Explanation

querySelector() selects the first element matching a CSS selector.

Code:

const title = document.querySelector('#title');
const firstBox = document.querySelector('.box');

Explanation

querySelector() can select elements using tags, classes, IDs, and complex CSS selectors.

Code:

document.querySelector('p');
document.querySelector('.card');
document.querySelector('#login');
document.querySelector('.menu li');

Explanation

querySelector() returns null when no matching element is found.

Code:

const element = document.querySelector('#missing');

if (element) {
  console.log(element);
}

Explanation

getElementById() is specialized for IDs, while querySelector() provides more flexible CSS selector-based searching.

Code:

document.getElementById('title');

document.querySelector('#title');
document.querySelector('.title');
document.querySelector('h1');

πŸš€ 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