Lesson 2 / الدرس 2

Selecting elements / اختيار العناصر

Before you can change anything you have to find it. Two methods cover almost everything, and they use the CSS selectors you already know from a whole course of them.

قبل أن تغيّر شيئًا عليك إيجاده. وطريقتان تغطيان كل شيء تقريبًا، وتستخدمان مُحدِّدات CSS التي تعرفها من دورة كاملة عنها.

document.querySelector('.price')         the FIRST match, or null
document.querySelectorAll('.price')      ALL matches, as a list

Any CSS selector works:
  '#total'            an id
  '.card .price'      a descendant
  'input[type=email]' an attribute
  'li:first-child'    a pseudo-class
Everything you learned in the CSS course transfers directly — the selector language is the same one. That is why these two methods replaced the older family of getElementsByClassName and friends. Run the demonstration.

Searching inside one element

Both methods exist on every element, not only on document. card.querySelector("h3") searches inside that card only, which is how you handle a page with twenty cards without giving every heading a unique id. This is the single most useful thing in the lesson and beginners rarely notice it.

What each one hands back

MethodGives backWhen nothing matches
querySelectorOne elementnull
querySelectorAllA list, alwaysAn empty list, length 0
getElementByIdOne elementnull
element.closest(".card")The nearest matching ancestornull
element.matches(".active")true or falsefalse

The fourth row is worth remembering now because lesson 8 depends on it: closest walks up the tree from an element until it finds a match, which is exactly what you need when someone clicks a button inside a card and you want the card.

One more thing about the list it returns: it is a snapshot, taken at the moment you asked. Add a matching element to the page afterwards and your list does not grow. That is usually what you want, and it means a list you stored in a variable at the top of a script may be out of date by the time you use it — which lesson 5 will make concrete.

Try it live / جرّب بنفسك

Preview / المعاينة

Check yourself / اختبر نفسك

1. What does querySelectorAll return when nothing matches?

2. Nothing happens and no error appears after querySelectorAll(".x").textContent = "hi". Why?

3. You have twenty cards and want the heading inside one of them. What is cleanest?

Your task / مهمتك

Take a page with several repeated blocks — cards, list items, table rows. Without changing the HTML, use JavaScript to report: how many of the repeated blocks there are, the text of the first one, the text of the last one, and the heading inside the third one found by searching within that block rather than by a unique id. Then use a selector that matches nothing and show what you get back from each of the two methods.

خذ صفحة فيها عدة كتل مكررة — بطاقات أو عناصر قائمة أو صفوف جدول. ودون تغيير HTML، استخدم JavaScript للإبلاغ عن: كم كتلة مكررة، ونص الأولى، ونص الأخيرة، والعنوان داخل الثالثة موجودًا بالبحث داخل تلك الكتلة لا بمعرّف فريد. ثم استخدم مُحدِّدًا لا يطابق شيئًا وأظهر ما تحصل عليه من الطريقتين.

  • A count, a first, and a last عدد وأول وآخر
  • One element found by searching inside another عنصر موجود بالبحث داخل آخر
  • No unique ids added to the HTML لا معرّفات فريدة أُضيفت إلى HTML
  • Both methods shown against a selector that matches nothing الطريقتان معروضتان مع مُحدِّد لا يطابق شيئًا
How do you want to submit? / كيف تريد التسليم؟