Javascript querySelector
Created By: chatGPT
The
querySelector
method is a powerful tool in the JavaScript DOM (Document Object Model) that allows you to select the first element matching a specified CSS selector. This method is particularly useful for simplifying the process of DOM manipulation.const element = document.querySelector('.my-class');
You can select elements by their ID, classes, attributes, or any valid CSS selector. For example, if you want to select an element by its ID, you can use the
#
prefix, followed by the ID name.const header = document.querySelector('#main-header');
Selecting multiple classes can be done by chaining class names together. For example, if you need to select an element with multiple classes, you can do it like this:
const button = document.querySelector('.btn.primary');
If you want to select an element based on an attribute, you can use square brackets. For example, selecting an input element with a specific type can be achieved by the following:
const input = document.querySelector('input[type="text"]');
Once you have selected an element, you can manipulate it using JavaScript methods. For example, you can change its text content or styles.
element.textContent = 'Hello, World!';
Remember that
querySelector
only returns the first matching element. If you need to select all matching elements, you can use querySelectorAll
, which returns a static NodeList of elements.const items = document.querySelectorAll('.item');
Here’s a complete example demonstrating how to use
querySelector
to change the background color of a div element with a specific class.const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';