Back to JavaScript
2026-03-058 min read

Selector Functions (JavaScript)

Learn Selector Functions (JavaScript) step by step with clear examples and exercises.

Why This Matters

JavaScript selector functions are an essential part of web development, enabling developers to dynamically manipulate HTML elements without reloading the page. These functions simplify complex tasks, create interactive websites with a better user experience, and help troubleshoot real-world bugs that require element selection and manipulation. Understanding JavaScript selector functions is crucial for preparing for interviews, exams focusing on web development and JavaScript, and staying competitive in today's fast-paced digital landscape.

Prerequisites

Before diving into JavaScript selector functions, it is essential to have a solid understanding of the following concepts:

  1. HTML (HyperText Markup Language) - the standard markup language for creating web pages.
  2. CSS (Cascading Style Sheets) - used to style and layout HTML elements.
  3. JavaScript fundamentals - variables, functions, loops, control structures, and basic DOM manipulation.
  4. Document Object Model (DOM) - a programming interface for HTML and XML documents.
  5. Familiarity with CSS selectors - understanding how to target specific HTML elements using CSS selectors is crucial when working with JavaScript selector functions.
  6. Understanding the basics of event handling in JavaScript, as many scenarios involving selector functions require reacting to user interactions like clicks or keypresses.
  7. Basic knowledge of browser developer tools, such as the console and inspector, for debugging and testing your code.

Core Concept

JavaScript selector functions allow you to select specific HTML elements based on their attributes or position within the DOM. The most commonly used selector functions are:

  1. document.getElementById() - returns the first element with the specified ID.
  2. document.getElementsByClassName() - returns a collection of all elements with the specified class name.
  3. document.getElementsByTagName() - returns a collection of all elements with the specified tag name.
  4. querySelector() and querySelectorAll() - more flexible selector functions that allow you to select elements based on CSS selectors.
  5. getElementByIdByName(), getElementsByClassNameAndTagName(), and custom selector functions (using regular expressions or other methods) for specific use cases.

Example: Using JavaScript Selector Functions

// Select the first paragraph by ID
const para1 = document.getElementById('para1');
console.log(para1);

// Select all paragraphs with the class 'example'
const exampleParas = document.getElementsByClassName('example');
for (let i = 0; i < exampleParas.length; i++) {
console.log(exampleParas[i]);
}

// Select all links by tag name
const links = document.getElementsByTagName('a');
for (let i = 0; i < links.length; i++) {
console.log(links[i]);
}

// Use querySelectorAll to select all elements with the class 'highlight' and an ID starting with 'item'
const highlightedItems = document.querySelectorAll('.highlight[id^="item"]');
for (let i = 0; i < highlightedItems.length; i++) {
console.log(highlightedItems[i]);
}

Core Concept - Advanced Topics

Custom Selector Functions

To create custom selector functions, you can use regular expressions or other methods to target specific HTML elements based on their attributes or content. For example:

function getElementsByAttribute(attributeName, attributeValue) {
const elements = document.getElementsByTagName('*');
const matchedElements = [];

for (let i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attributeName) === attributeValue) {
matchedElements.push(elements[i]);
}
}

return matchedElements;
}

Event-driven Selector Functions

In addition to selecting elements, JavaScript selector functions can also be used in conjunction with event handling to create interactive web applications. For example:

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

changeColorButton.addEventListener('click', () => {
const exampleParas = document.getElementsByClassName('example');
for (let i = 0; i < exampleParas.length; i++) {
const para = exampleParas[i];
para.style.backgroundColor = getRandomColor();
}
});

Worked Example

Let's create a simple webpage with a button that changes the background color of all paragraphs when clicked:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Selector Functions</title>
</head>
<body>
<button id="changeColorButton">Change Paragraph Colors</button>
<p class="example" id="para1">Paragraph 1</p>
<p class="example" id="para2">Paragraph 2</p>
<script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

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

changeColorButton.addEventListener('click', () => {
const exampleParas = document.getElementsByClassName('example');
for (let i = 0; i < exampleParas.length; i++) {
const para = exampleParas[i];
para.style.backgroundColor = getRandomColor();
}
});

function getRandomColor() {
return '#' + Math.floor(Math.random()*16777215).toString(16);
}

Common Mistakes

  1. Not enclosing CSS selectors in quotes: Remember to put your CSS selector strings within single or double quotes when using querySelector() and querySelectorAll().
  2. Missing the parentheses for getElementById(): Ensure you include the parentheses after the function name when using document.getElementById().
  3. Not checking if an element was found: Before manipulating a selected element, always check if it exists by using the length property or a conditional statement.
  4. Misunderstanding the difference between getElementById(), getElementsByClassName(), and getElementsByTagName(): These functions return different types of objects: getElementById() returns a single element, while getElementsByClassName() and getElementsByTagName() return collections of elements.
  5. Not using querySelectorAll() for complex selectors: If your CSS selector is complex or requires multiple conditions, use querySelectorAll() instead of querySelector(), as it returns a NodeList, which can be more useful in some cases.
  6. Incorrectly handling NodeLists: Remember that NodeLists are not arrays, so you cannot directly access elements using array-like notation (e.g., nodeList[0]). Instead, use a loop or forEach() method to iterate through the NodeList.
  7. Not considering case sensitivity in CSS selectors: Be aware that CSS selectors are case-sensitive when using JavaScript selector functions.
  8. Forgetting to include the script tag: Make sure your JavaScript file is properly linked in the HTML document, or include it directly within a `` tag if it's small enough.
  9. Not handling errors gracefully: Always handle potential errors, such as when trying to select an element that doesn't exist, by using try-catch blocks or other error-handling techniques.
  10. Ignoring browser compatibility issues: Be aware of the different levels of support for JavaScript selector functions across various browsers and ensure your code is compatible with the browsers you intend to target.
  11. Not properly escaping special characters in CSS selectors: When using querySelector() or querySelectorAll(), make sure to escape any special characters (like spaces, square brackets, and parentheses) using their corresponding escape sequences (e.g., \ for a space).
  12. Not considering the order of operations when combining multiple selectors: Be aware that the order in which you combine selectors using CSS operators like , (comma), > (child combinator), or + (adjacent sibling combinator) can affect the results of your selector.
  13. Not considering the specificity of CSS selectors: When multiple CSS rules target the same element, the one with higher specificity will take precedence. Be aware of this when using JavaScript to manipulate elements based on their CSS classes or IDs.
  14. Not accounting for dynamic content: If your webpage contains dynamically generated HTML elements, make sure to use event listeners or other techniques to ensure that your selector functions can still target these elements effectively.

Practice Questions

  1. Write JavaScript code to change the text color of all paragraphs with an ID starting with 'header'.
  2. Create a script that hides all links with the class 'external' and displays them when the user clicks on a button.
  3. Write code to count the number of images (``) on your webpage using JavaScript.
  4. Given the following HTML structure, use JavaScript to change the background color of the third list item in the unordered list with an ID 'navbar'.
<ul id="navbar">
<li>Item 1</li>
<li>Item 2</li>
<!-- More items here -->
</ul>
  1. Write a JavaScript function that highlights all elements with the class 'highlight' when the user clicks on them.
  2. Create a script that changes the text of all headings (`, , ..., `) to uppercase when the user clicks a button.
  3. Write JavaScript code to create a new paragraph with the text "Hello, World!" and append it as the last child of the body element.
  4. Given the following HTML structure, use JavaScript to find the total number of links within the navigation bar (the unordered list with an ID 'navbar').
<ul id="navbar">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<!-- More links here -->
</ul>

FAQ

Q: What is the difference between querySelector() and querySelectorAll()?

A: querySelector() returns the first matched element, while querySelectorAll() returns a NodeList containing all elements that match the specified selector.

Q: Can I use JavaScript to select HTML elements based on their content or attributes other than ID, class, and tag name?

A: Yes! With CSS selectors, you can target elements based on various attributes like href, src, title, and more. You can also target elements using pseudo-classes like :hover or :active. Additionally, custom selector functions can be created using regular expressions or other methods to target specific HTML elements based on their attributes or content.

Q: How do I remove a specific class from an element using JavaScript?

A: To remove a class from an element, use the classList property and call the remove() method with the name of the class you want to remove. For example:

const myElement = document.getElementById('my-element');
myElement.classList.remove('example-class');

Q: How do I add a new CSS rule using JavaScript?

A: To add a new CSS rule using JavaScript, you can use the style property of an HTML element or create a new `` tag and append it to the head of your document. For example:

const body = document.querySelector('body');
body.style.backgroundColor = 'red'; // Adding a CSS rule directly to the body

// Creating a new <style> tag and appending it to the head
const styleTag = document.createElement('style');
styleTag.innerHTML = `
.highlight {
color: yellow;
}
`;
document.head.appendChild(styleTag);

Q: How can I use JavaScript selector functions to create a responsive web design?

A: JavaScript selector functions can be used in conjunction with media queries and CSS to create a responsive web design. For example, you can use window.matchMedia() to check the viewport size and adjust your HTML elements accordingly using JavaScript selector functions. Additionally, you can use JavaScript to dynamically add or remove classes from HTML elements based on the current viewport size, which can be used in your CSS media queries to apply different styles for different screen sizes.

Selector Functions (JavaScript) | JavaScript | XQA Learn