JavaScript selectors are a fundamental part of interacting with the Document Object Model (DOM). They allow you to target and manipulate HTML elements in your web page. Selectors can be used to find elements by their tag names, classes, IDs, attributes, and more.
You can select elements using various methods, including:
document.getElementsByTagName()
.document.getElementsByClassName()
.document.getElementById()
.
// Selecting elements by tag name
const headings = document.getElementsByTagName('h1'); // Returns an HTMLCollection
// Selecting elements by class name
const elementsWithClass = document.getElementsByClassName('my-class'); // Returns an HTMLCollection
// Selecting an element by ID
const uniqueElement = document.getElementById('unique-id'); // Returns an Element
// Using querySelector to select elements by ID, class, and more
const elementById = document.querySelector('#my-id'); // Selects element with ID 'my-id'
const elementsByClass = document.querySelectorAll('.my-class'); // Selects all elements with class 'my-class'
const firstParagraph = document.querySelector('p'); // Selects the first paragraph element
You can combine selectors to target elements more precisely. For instance, you can use CSS-style selectors, such as:
// Combining selectors using querySelector and querySelectorAll
const element = document.querySelector('tag.class'); // Returns the first matching element
const elements = document.querySelectorAll('.class1.class2'); // Returns a NodeList
You can select elements based on their attributes. For example, to select all elements with a specific data attribute, you can use:
// Selecting elements based on attributes
const elementsWithAttribute = document.querySelectorAll('[data-attribute="value"]'); // Returns a NodeList
Pseudo-classes allow you to select elements based on their state or position. Some common pseudo-classes include :hover, :active, and :nth-child(n).
// Using pseudo-class selectors
const hoveredElements = document.querySelectorAll(':hover'); // Returns a NodeList
const oddElements = document.querySelectorAll(':nth-child(odd)'); // Returns a NodeList
You can navigate the DOM tree using traversal methods. For example, to select a child element, you can use:
// Traversal and hierarchical selectors
const parent = document.querySelector('.parent');
const child = parent.querySelector('.child');
You can also select elements based on events. For instance, to select all buttons, you can use:
// Selecting elements based on events
const buttons = document.querySelectorAll('button'); // Returns a NodeList
Select element by ID
const elementById = document.querySelector('#element-id');
Select elements by class
const elementsByClass = document.querySelectorAll('.element-class');
Select elements by tag name
const elementsByTag = document.querySelectorAll('p');
Select elements by attribute
const elementsByAttribute = document.querySelectorAll('[data-custom]');
Select the first element with a class
const firstElementByClass = document.querySelector('.first-element-class');
Select the last child of an element
const lastChild = document.querySelector('.container :last-child');
Select all even list items
const evenListItems = document.querySelectorAll('li:nth-child(even)');
Select elements within a specific container
const containerElements = document.querySelectorAll('.container p');
Select elements with a specific data attribute within a container
const customElements = document.querySelectorAll('.container [data-custom]');
Select the first child of an element
const firstChild = document.querySelector('.container :first-child');
Select elements with a specific class and tag name
const specificElements = document.querySelectorAll('div.special-class');
Select the first element with a specific class and tag name
const firstSpecificElement = document.querySelector('div.special-class');
Select elements with a specific class and data attribute
const specificCustomElements = document.querySelectorAll('.special-class[data-custom]');
Select the parent of a specific element
const parentElement = document.querySelector('.child-element').parentElement;
Select the next sibling of a specific element
const nextSibling = document.querySelector('.element').nextElementSibling;
Adding a click event listener to an element
const button = document.querySelector('#myButton');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
Iterating over a NodeList
const elements = document.querySelectorAll('.item');
elements.forEach((element) => {
console.log(element.textContent);
});
Iterating over an array and creating elements
const data = ['Apple', 'Banana', 'Cherry'];
const list = document.querySelector('#myList');
data.forEach((item) => {
const listItem = document.createElement('li');
listItem.textContent = item;
list.appendChild(listItem);
});
Selecting elements and attaching click events
const buttons = document.querySelectorAll('.myButton');
buttons.forEach((button) => {
button.addEventListener('click', () => {
console.log('Button clicked!');
});
});
Filtering and iterating over elements
const paragraphs = document.querySelectorAll('p');
paragraphs.forEach((paragraph) => {
if (paragraph.classList.contains('special')) {
console.log(paragraph.textContent);
}
});
Adding click events to elements selected by class
const elements = document.querySelectorAll('.clickable');
elements.forEach((element) => {
element.addEventListener('click', () => {
console.log('Element clicked:', element.textContent);
});
});
JavaScript selectors are powerful tools for interacting with the DOM. They enable you to target specific elements, combine selectors for precision, select based on attributes or pseudo-classes, navigate the DOM tree, and even select elements based on events. Understanding selectors is crucial for dynamic web applications.