📘 Lesson · Lesson 33
Selecting Elements
Elements Select करना
Finding Elements First
Before you can change anything on a page, you must first GRAB the element you want. This is always step one of DOM work: select, then modify. JavaScript gives you several selection methods, all starting from
document. The good news — you already know how to describe which element you want, because these methods use CSS selectors, exactly the ones from the CSS course. If you can write .card or #header in a stylesheet, you can select those same elements in JavaScript.getElementById — the classic
<h1 id="title">Hello</h1>
let heading = document.getElementById("title"); // no # symbol!
console.log(heading); // <h1 id="title">Hello</h1>
heading.textContent = "Changed!"; // now use it
let missing = document.getElementById("nothing"); // null if not found
getElementById() finds the single element with that id — the oldest and fastest selection method. Note carefully: you pass just the id name, without the # (unlike CSS). Since ids are unique, it returns exactly one element, or null if no match exists. That null matters: trying to use a null element (null.textContent) throws an error — one of the most common DOM crashes, usually caused by a typo in the id, or by running your script before the HTML loaded (remember: put scripts before </body> or use defer).querySelector — the modern all-rounder
<div class="card"><p>Hi</p></div>
// Uses CSS selector syntax — with the # and . symbols!
document.querySelector("#title"); // by id
document.querySelector(".card"); // by class
document.querySelector("p"); // by tag
document.querySelector(".card p"); // descendant, just like CSS
document.querySelector("input[type='text']"); // attribute selector
// Returns the FIRST match only, or null
querySelector() accepts any CSS selector and returns the FIRST matching element — making it by far the most flexible and widely used selection method today. Anything you can target in CSS, you can select here: ids, classes, tags, descendants, attributes, pseudo-classes. Unlike getElementById, you DO include the # and . symbols. If nothing matches, it returns null. This single method can replace all the older ones, which is why modern code uses it almost exclusively.querySelectorAll — selecting many elements
<li class="item">A</li>
<li class="item">B</li>
let items = document.querySelectorAll(".item");
console.log(items.length); // 2 — it's a list (a NodeList)
console.log(items[0]); // the first li
// You must LOOP to change them all:
items.forEach(item => item.style.color = "red");
items.style.color = "red"; // ✗ ERROR — a list has no .style!
querySelectorAll() returns ALL matching elements as a NodeList — a list you can loop over. Here's the mistake nearly every beginner makes: a NodeList is NOT a single element, so you can't set .style or .textContent on it directly. You must loop through it and change each element individually — forEach works perfectly here. A NodeList looks like an array and supports forEach and length, but it isn't a true array (no map or filter); convert it with [...items] if you need those.Which Method to Use
| Method | Returns | Selector style |
|---|---|---|
| getElementById("x") | One element or null | Plain id, no # |
| querySelector(".x") | First match or null | Any CSS selector |
| querySelectorAll(".x") | NodeList of all matches | Any CSS selector |
| getElementsByClassName("x") | Live HTMLCollection | Plain class name |
| getElementsByTagName("p") | Live HTMLCollection | Plain tag name |
Practical guidance: use
querySelector for one element and querySelectorAll for many. They handle every case with familiar CSS syntax, so you only need to remember two methods. getElementById remains fine (and marginally faster) when you have an id. The older getElementsBy... methods return a "live" HTMLCollection that updates automatically as the page changes — occasionally useful, but the behaviour surprises people, and they lack forEach. Stick with the querySelector pair and you'll rarely go wrong.Exam Corner
Q: What does getElementById return if nothing matches? null.
Q: Do you include the # with getElementById? No — just the id name. querySelector DOES need the #.
Q: What does querySelector return? The first element matching the CSS selector, or null.
Q: What does querySelectorAll return? A NodeList of all matches — you must loop to modify them.
Q: Why does
Q: Do you include the # with getElementById? No — just the id name. querySelector DOES need the #.
Q: What does querySelector return? The first element matching the CSS selector, or null.
Q: What does querySelectorAll return? A NodeList of all matches — you must loop to modify them.
Q: Why does
querySelectorAll(".x").style.color = "red" fail? Because a NodeList is a list, not a single element.
पहले Elements ढूंढना
Page पर कुछ भी बदलने से पहले, आपको वह element PAKADNA होगा जो आप चाहते हैं. DOM काम का यह हमेशा पहला कदम है: select कीजिए, फिर modify. JavaScript आपको कई selection methods देता है, सब
document से शुरू. अच्छी खबर — आप पहले से जानते हैं कैसे बताएं कौन-सा element चाहिए, क्योंकि ये methods CSS selectors use करते हैं, ठीक वही जो CSS course से. अगर आप stylesheet में .card या #header लिख सकते हैं, तो उन्हीं elements को JavaScript में select कर सकते हैं.getElementById — classic
<h1 id="title">Hello</h1>
let heading = document.getElementById("title"); // koi # symbol nahi!
console.log(heading); // <h1 id="title">Hello</h1>
heading.textContent = "Changed!"; // ab use karo
let missing = document.getElementById("nothing"); // na mile to null
getElementById() उस id वाला अकेला element ढूंढता है — सबसे पुराना और तेज़ selection method. ध्यान से देखिए: आप सिर्फ id नाम भेजते हैं, # के बिना (CSS के उलट). चूंकि ids unique हैं, यह ठीक एक element लौटाता है, या match न होने पर null. वह null मायने रखता है: null element use करने की कोशिश (null.textContent) error फेंकती है — सबसे common DOM crashes में से एक, आमतौर पर id में typo से, या HTML load होने से पहले script चलाने से (याद रखिए: scripts </body> से पहले रखिए या defer use कीजिए).querySelector — आधुनिक all-rounder
<div class="card"><p>Hi</p></div>
// CSS selector syntax use karta hai — # aur . symbols ke saath!
document.querySelector("#title"); // id se
document.querySelector(".card"); // class se
document.querySelector("p"); // tag se
document.querySelector(".card p"); // descendant, bilkul CSS jaisa
document.querySelector("input[type='text']"); // attribute selector
// Sirf PEHLA match lautata hai, ya null
querySelector() कोई भी CSS selector स्वीकार करता है और PEHLA मिलता element लौटाता है — जो इसे आज तक का सबसे लचीला और व्यापक रूप से इस्तेमाल किया selection method बनाता है. जो कुछ आप CSS में target कर सकते हैं, यहां select कर सकते हैं: ids, classes, tags, descendants, attributes, pseudo-classes. getElementById के उलट, आप # और . चिन्ह शामिल KARTE हैं. कुछ match न हो तो यह null लौटाता है. यह अकेला method सारे पुराने वालों की जगह ले सकता है, इसीलिए modern code लगभग पूरी तरह इसे use करता है.querySelectorAll — कई elements select करना
<li class="item">A</li>
<li class="item">B</li>
let items = document.querySelectorAll(".item");
console.log(items.length); // 2 — yeh list hai (NodeList)
console.log(items[0]); // pehla li
// Sab badalne ko LOOP karna zaruri:
items.forEach(item => item.style.color = "red");
items.style.color = "red"; // ✗ ERROR — list ki koi .style nahi!
querySelectorAll() सारे मिलते elements NodeList के रूप में लौटाता है — एक list जिस पर आप loop कर सकते हैं. यहां वह गलती है जो लगभग हर beginner करता है: NodeList एकल element NAHI है, तो आप उस पर सीधे .style या .textContent set नहीं कर सकते. आपको उस पर loop करके हर element अलग से बदलना होगा — forEach यहां perfectly चलता है. NodeList array जैसा दिखता है और forEach तथा length support करता है, पर यह असली array नहीं (कोई map या filter नहीं); वे चाहिए तो [...items] से बदलिए.कौन-सा Method Use करें
| Method | लौटाता है | Selector style |
|---|---|---|
| getElementById("x") | एक element या null | सादा id, # नहीं |
| querySelector(".x") | पहला match या null | कोई भी CSS selector |
| querySelectorAll(".x") | सारे matches की NodeList | कोई भी CSS selector |
| getElementsByClassName("x") | Live HTMLCollection | सादा class नाम |
| getElementsByTagName("p") | Live HTMLCollection | सादा tag नाम |
व्यावहारिक मार्गदर्शन: एक element के लिए
querySelector और कई के लिए querySelectorAll use कीजिए. वे परिचित CSS syntax से हर मामला संभालते हैं, तो आपको सिर्फ दो methods याद रखने हैं. getElementById ठीक (और थोड़ा तेज़) रहता है जब आपके पास id हो. पुराने getElementsBy... methods "live" HTMLCollection लौटाते हैं जो page बदलने पर अपने आप update होता है — कभी-कभार उपयोगी, पर व्यवहार लोगों को चौंकाता है, और उनमें forEach नहीं. querySelector जोड़ी पर टिकिए और शायद ही गलत होंगे.Exam Corner
Q: कुछ match न हो तो getElementById क्या लौटाता है? null.
Q: क्या getElementById के साथ # शामिल करते हैं? नहीं — सिर्फ id नाम. querySelector को # चाहिए.
Q: querySelector क्या लौटाता है? CSS selector से मिलता पहला element, या null.
Q: querySelectorAll क्या लौटाता है? सारे matches की NodeList — बदलने को loop करना होगा.
Q:
Q: क्या getElementById के साथ # शामिल करते हैं? नहीं — सिर्फ id नाम. querySelector को # चाहिए.
Q: querySelector क्या लौटाता है? CSS selector से मिलता पहला element, या null.
Q: querySelectorAll क्या लौटाता है? सारे matches की NodeList — बदलने को loop करना होगा.
Q:
querySelectorAll(".x").style.color = "red" fail क्यों होता है? क्योंकि NodeList list है, एकल element नहीं.
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.