JavaScript Selectors

About JavaScript Selector

JavaScript selectors are functions used to select HTML elements so that we can read/access or modify them using JavaScript. The DOM (Document Object Model) provides these methods to select elements from an HTML document.

Why Use Selectors?

Selectors are essential for interacting with the DOM. They allow you to select elements based on their ID, class, tag name, or other attributes, enabling you to read or modify their content, styles, and behavior dynamically.

Mastering JavaScript selectors is fundamental to effective DOM manipulation.

Most Common JavaScript Selector Methods

JavaScript provides several methods to select elements from the DOM. Here are some of the most commonly used selector methods:

Basic Selectors
  • getElementById(): Selects a single element by its unique id attribute.
  • getElementsByClassName(): Selects all elements that have a specific class name.
  • getElementsByTagName(): Selects all elements with a specific tag name (e.g., div, p, a).
Advanced Modern Selectors
  • querySelector(): Selects the first element that matches a CSS-style selector.
  • querySelectorAll(): Selects all elements that match a CSS-style selector.

getElementById('id') Method

The getElementById() method is used to select a single HTML element by its unique id attribute. It returns the first element with the specified id or null if no such element exists.

This method is commonly used to manipulate or retrieve information from a specific element in the DOM.

id should be unique within an HTML document. This method is very efficient for targeting a specific element.

Here is an example of how to use the getElementById() method:

Demonstration of Above Example

When you click the button below, an alert will pop up with the message "Welcome to xfactorschool.com!"


Welcome to xfactorschool.com!

Explanation of the Code
  • const greetingElement = document.getElementById('greeting');: This line selects the div element with the id greeting from the DOM.
  • alert(greetingElement.textContent);: This line retrieves the text content of the selected element and displays it in an alert box.

getElementsByClassName('className') Method

The getElementsByClassName() method is used to select all HTML elements that have a specific class name. It returns a live HTMLCollection of elements with the specified class name.

This method is useful when you want to manipulate or retrieve information from multiple elements that share the same class.

The class attribute can be used to apply styles or behaviors to multiple elements at once. This method returns a live collection, meaning that if the DOM changes, the collection updates automatically.

Here is an example of how to use the getElementsByClassName() method:

Demonstration of Above Example

When you click the button below, the color of the text in the items will change to red, and the font size will increase to 25 pixels.


Item 1
Item 2

Explanation of the Code
  • const items = document.getElementsByClassName('item');: This line selects all elements with the class item from the DOM.
  • for (let i = 0; i < items.length; i++) {...}: This loop iterates through each element in the collection to modify the elements' styles.
  • items[i].style.color = 'red';: This line changes the text color of each selected element to red.
  • items[i].style.fontSize = '25px';: This line changes the font size of each selected element to 25 pixels.

getElementsByTagName('tagname') Method

The getElementsByTagName() method is used to select all HTML elements with a specific tag name. It returns a live HTMLCollection of elements with the specified tag name.

This method is useful when you want to manipulate or retrieve information from multiple elements that share the same tag name, such as div, p, or a.

The tag name is the name of the HTML element, and this method returns a live collection, meaning that if the DOM changes, the collection updates automatically.

Here is an example of how to use the getElementsByTagName() method:

Demonstration of Above Example

When you click the button below, the text color of the paragraphs will change to green, the font size will increase to 20 pixels, and the font weight will become bold.


First Paragraph

Second Paragraph

Third Paragraph


Explanation of the Code
  • const paras = document.getElementsByTagName('p');: This line selects all elements with the tag name p from the DOM.
  • for (let i = 0; i < paras.length; i++) {...}: This loop iterates through each element in the collection to modify the elements' styles.
  • paras[i].style.color = 'green';: This line changes the text color of each selected paragraph to green.
  • paras[i].style.fontSize = '20px';: This line changes the font size of each selected paragraph to 20 pixels.
  • paras[i].style.fontWeight = 'bold';: This line changes the font weight of each selected paragraph to bold.

querySelector('selector') Method

The querySelector() method is a powerful and modern selector that allows you to select the first element that matches a CSS-style selector. It can be used to select elements by their class, id, tag name, or any other valid CSS selector.

This method is very flexible and can be used to select elements in a way similar to how you would use CSS selectors in stylesheets.

The querySelector() method returns the first matching element or null if no such element exists. It is widely used in modern JavaScript development for its simplicity and versatility.

Here is an example of how to use the querySelector() method:

Demonstration of Above Example

When you click the button below, an alert will pop up with the text of the first paragraph "First Paragraph".


First Paragraph

Second Paragraph

Third Paragraph


Explanation of the Code
  • const para = document.querySelector('.para');: This line selects the first element with the class para from the DOM.
  • alert(para.innerText);: This line retrieves the text content of the selected element and displays it in an alert box.

querySelectorAll('selector') Method

The querySelectorAll() method is similar to querySelector(), but it selects all elements that match a CSS-style selector.

This method returns a NodeList, which is a non-live collection (it doesn't automatically update if the DOM changes) of the matching elements.

This method is useful when you want to select multiple elements that share the same class, id, tag name, or any other valid CSS selector.

The querySelectorAll() method allows you to use complex CSS selectors, making it a powerful tool for selecting elements in the DOM.

Here is an example of how to use the querySelectorAll() method:

Demonstration of Above Example

When you click the button below, an alert will pop up with the notes of all the selected elements.


Note from John

Note from Peter

Note from Paul


Explanation of the Code
  • const notes = document.querySelectorAll('.note');: This line selects all elements with the class note from the DOM.
  • let allNotes = '';: This line initializes an empty string to store the concatenated text of all selected notes.
  • notes.forEach(note => {...});: This line iterates through each selected note and concatenates its text to the allNotes string.
  • alert(allNotes);: This line displays all concatenated notes in an alert box.
Live vs Static Collections

getElementsByClassName() and getElementsByTagName() methods return live collections. This means that if the DOM changes, the collection updates automatically.

querySelectorAll() method returns a static NodeList. This means that if the DOM changes after the selection, the NodeList does not update automatically.

Traversing Selected Elements

Traversing selected elements in JavaScript means navigating through the DOM (Document Object Model) tree to access or manipulate elements relative to a selected one.

This is useful when you want to move between parents, children, or siblings of a selected element.

Here is an example of how to traverse selected element:

Explanation of the Code
  • child.parentElement: This line traverses to the parent element of the selected child element.
  • parent.children: This line accesses the child elements of the parent element.
  • parent.firstElementChild: This line accesses the first child element of the parent element.
  • parent.lastElementChild: This line accesses the last child element of the parent element.
  • child.nextElementSibling: This line accesses the next sibling element of the selected child element.
  • parentElement.closest('.container'): This line finds the closest ancestor of the parentElement that matches the selector '.container'.

Advanced CSS Selector Pattern

Universal Selector (*)

The universal selector (*) selects all elements in the document. It can be used to apply styles or behaviors to every element, but it is not commonly used for performance reasons.

Here is an example of how to use universal selector with the querySelectorAll() method:

Type Selector (tagname e.g. div, p, etc.)

The type selector selects elements based on their tag name. For example, div selects all div elements in the document.

Here is an example of how to use type selector with the querySelectorAll() method:

Class Selector (.classname)

The class selector selects elements based on their class attribute. For example, .box selects all elements with the class box.

Here is an example of how to use class selector with the querySelectorAll() method:

ID Selector (#id)

The ID selector selects an element based on its unique ID attribute. For example, #header selects the element with the ID header. IDs should be unique within a document.

Here is an example of how to use ID selector with the querySelector() method:

Group Selector (,)

The group selector allows you to select multiple elements at once by separating them with a comma. For example, div, p selects all div and p elements in the document.

Here is an example of how to use group selector with the querySelectorAll() method:

Descendant Selector (A B)

The descendant selector selects elements that are descendants of a specified element. For example, div p selects all p elements that are inside a div element.

Here is an example of how to use descendant selector with the querySelectorAll() method:

Child Selector (A > B)

The child selector selects elements that are direct children of a specified element. For example, div > p selects all p elements that are direct children of a div element.

Here is an example of how to use descendant selector with the querySelectorAll() method:

Adjacent Sibling Selector (A + B)

The adjacent sibling selector selects an element that is immediately following another specified element. For example, h2 + p selects the first p element that is immediately after an h2 element.

This selector is useful when you want to target an element that comes directly after another element in the DOM.

Here is an example of how to use adjacent sibling selector with the querySelectorAll() method:

General Sibling Selector (A ~ B)

The general sibling selector selects all elements that are siblings of a specified element. For example, h2 ~ p selects all p elements that are siblings of an h2 element.

This selector is useful when you want to target all elements that come after a specified element, regardless of whether they are immediately adjacent or not.

Here is an example of how to use general sibling selector with the querySelectorAll() method:

Attribute Selector

The attribute selector allows you to select elements based on the presence or value of an attribute. For example, input[type='text'] selects all input elements with a type attribute equal to text.

This selector is useful when you want to target elements based on specific attributes, such as type, href, name or any custom attribute.

Here is an example of how to use attribute selector with the querySelectorAll() method:

Attribute Contains ([attr*='value'])

The attribute contains selector allows you to select elements whose attribute value contains a specified substring. For example, a[href*='example'] selects all a elements with an href attribute that contains the substring example.

This selector is useful when you want to target elements based on partial matches of attribute values.

Here is an example of how to use attribute contains selector with the querySelectorAll() method:

Attribute Starts With ([attr^='value'])

The attribute starts with selector allows you to select elements whose attribute value starts with a specified substring. For example, img[src^='https://'] selects all img elements with a src attribute that starts with https://.

This selector is useful when you want to target elements based on the beginning of attribute values.

Here is an example of how to use attribute starts with selector with the querySelectorAll() method:

Attribute Ends With ([attr$='value'])

The attribute ends with selector allows you to select elements whose attribute value ends with a specified substring. For example, img[src$='.jpg'] selects all img elements with a src attribute that ends with .jpg.

This selector is useful when you want to target elements based on the ending of attribute values.

Here is an example of how to use attribute ends with selector with the querySelectorAll() method:

Structural Pseudo-class Selectors

:first-child

The pseudo-class selector :first-child selects the first child element of its parent. For example, li:first-child selects the first li element within a parent element.

This selector is useful when you want to apply styles or behaviors to the first child of a specific parent element.

Here is an example of how to use the :first-child pseudo-class selector with the querySelector() method:

:last-child

The pseudo-class selector :last-child selects the last child element of its parent. For example, li:last-child selects the last li element within a parent element.

This selector is useful when you want to apply styles or behaviors to the last child of a specific parent element.

Here is an example of how to use the :last-child pseudo-class selector with the querySelector() method:

:nth-child(n)

The pseudo-class selector ::nth-child(n) selects the nth child element of its parent. For example, li:nth-child(2) selects the second li element within a parent element.

This selector is useful when you want to apply styles or behaviors to the nth child of a specific parent element.

Here is an example of how to use the :nth-child(n) pseudo-class selector with the querySelector() method:

More structural pseudo-class selectors: :only-child, :nth-last-child(), :first-of-type, :last-of-type, :only-of-type, :nth-of-type(), and :nth-last-of-type()

Logical Pseudo-class Selector

:not(selector)

The :not(selector) pseudo-class selector selects elements that do not match the specified selector. For example, div:not(.box) selects all div elements that do not have the class box.

This selector is useful when you want to apply styles or behaviors to the element that do not match a specific condition.

Here is an example of how to use the :not(selector) pseudo-class selector with the querySelectorAll() method:

:is(selector)

The :is(selector) pseudo-class selector selects elements that match the specified selector. For example, div:is(.box) selects all div elements that have the class box.

This selector is useful when you want to apply styles or behaviors to the element that matches a specific condition.

Here is an example of how to use the :is(selector) pseudo-class selector with the querySelectorAll() method:

:where(selector)

The :where(selector) pseudo-class selector selects using multiple selectors without adding specificity. For example, div:where(header) selects all header elements.

This selector is useful when you want to apply styles or behaviors to multiple elements without adding specificity.

Here is an example of how to use the :where(selector) pseudo-class selector with the querySelectorAll() method:

:has(selector)

The :has(selector) pseudo-class selector selects elements that contain a specified selector. For example, div:has(img) selects all div elements that contain an img element.

This selector is useful when you want to apply styles or behaviors to elements that contain specific child elements.

Here is an example of how to use the :has(selector) pseudo-class selector with the querySelectorAll() method:

More logical pseudo-class selectors: :matches(), and :nth-match()

Form-related Pseudo-class Selector

:checked (for input type like checkbox/radio)

The :checked pseudo-class selector selects input elements that are checked, such as checkboxes or radio buttons. For example, input:checked selects all checked input elements.

This selector is useful when you want to apply styles or behaviors to the elements that are currently checked.

Here is an example of how to use the :checked pseudo-class selector with the querySelectorAll() method:

:disabled / :enabled

The :disabled pseudo-class selector selects input elements that are disabled, while the :enabled pseudo-class selector selects input elements that are enabled. For example, input:disabled selects all disabled input elements, and input:enabled selects all enabled input elements.

These selectors are useful when you want to apply styles or behaviors to the elements that are currently disabled or enabled.

Here is an example of how to use the :disabled & :enabled pseudo-class selectors with the querySelectorAll() method:

:required / :optional

The :required pseudo-class selector selects input elements that are required, while the :optional pseudo-class selector selects input elements that are optional. For example, input:required selects all required input elements, and input:optional selects all optional input elements.

These selectors are useful when you want to apply styles or behaviors to the elements that are currently required or optional.

Here is an example of how to use the :required & :optional pseudo-class selectors with the querySelectorAll() method:

More form-related pseudo-class selectors: :valid, :invalid, :selected, :in-range, :out-of-range, :placeholder-shown, :read-only, :read-write, :autofill, and :default

User action pseudo-class selectors: :active, :hover, :focus, :focus-visible and :focus-within

Other pseudo-class selectors: :root, :lang(), :dir(), :empty, :target, :playing and :paused

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more JavaScript selector examples in the following HTML code editor and click Execute button to check the output. The output will be displayed in HTML Code Output section.

JavaScript logo Online HTML Editor
HTML Code Output