The document.querySelector method in JavaScript is a powerful tool that allows you to select HTML elements based on their CSS selectors, making it easy to manipulate and style elements on a web page. One of the most straightforward ways to use this method is by selecting an element by its ID, which can be incredibly useful for targeting unique elements on a page. Let's dive into examples of how to use document.querySelector with IDs.

Before we start, let's ensure you understand the basics. In HTML, IDs are unique identifiers for elements, denoted by the '#' symbol. For instance, an HTML element might have an ID like this: id="uniqueElement". In this case, 'uniqueElement' is the ID.

Selecting Elements by ID
The basic syntax for selecting an HTML element by its ID using document.querySelector is as follows:

document.querySelector('#id');Example: Changing Background Color

Let's say we have the following HTML element with the ID 'myElement' in our document:
<h1 id="myElement">Hello, World!</h1>
We can select this element and change its background color to red using the style property like so:

document.querySelector('#myElement').style.backgroundColor = 'red';This snippet of code will change the background color of the 'Hello, World!' heading to red.
Example: Displaying and Hiding Elements

Another useful application of document.querySelector is toggling the visibility of elements. Let's say we have a paragraph with the ID 'hiddenText':
<p id="hiddenText" style="display: none;">This is a hidden paragraph.</p>




















We can select this element and toggle its visibility. Here's how you can show and hide this paragraph:
document.querySelector('#hiddenText').style.display = 'block'; // Showdocument.querySelector('#hiddenText').style.display = 'none'; // Hide
Selecting and Manipulating Multiple Elements with IDs
While IDs are unique, there might be occasions where you need to select multiple elements with the same ID. In such cases, document.querySelectorAll is the method you would use.
Example: Selecting and Manipulating Multiple Elements
Suppose you have a series of buttons, each with the same ID 'myButton', and you want to apply alijn anchorbell specific style to all of them:
<button id="myButton">Button 1</button> <button id="myButton">Button 2</button> <button id="myButton">Button 3</button>
You can select all these buttons and apply a style using a loop:
document.querySelectorAll('#myButton').forEach(button => {
button.style.color = 'blue';
});This will change the text color of all buttons with the ID 'myButton' to blue.
In conclusion, the document.querySelector method, along with its sibling document.QuerySelectorAll, provides powerful ways to interact with and manipulate HTML elements, especially when those elements are uniquely identified by their IDs.
Ready to dive deeper? Try experimenting with different stylings and behaviors, and don't forget to explore other selectors and methods to expand your toolkit. Happy coding!