skip to content
Dev Journal

Selecting an Element

/ 1 min read

To change a <div>s text color from black to red with JavaScript, you first need to select <div element using the querySelector method.

The document.querySelector method lets you select an element using CSS-Style selectors:

  • To select by id, prepend with #.
  • To select by class, prepend with ..
  • To select by tag, just write the tag name.
  • To select by attribute, use square brackets [].

Example:

<div id="master-shimotsuki">Shimotsuki</div>
<div class="class-of-samurai">Samurai</div>
<p>The lovely cat</p>
<div data-type="meteor">☄️</div>
document.querySelector("#master-shimotsuki") // <div id="master-shimotsuki">Shimotsuki</div>
document.querySelector(".class-of-samurai") // <div class="class-of-samurai">Samurai</div>
document.querySelector('p') // <p>The lovely cat</p>
document.querySelector('[data-type="meteor"]') // <div data-type="meteor">☄️</div>

querySelector returns the first matching element. For multiple elements, use querySelectorAll.

You can also use element.querySelector to search within a specific element, which is faster than searching the entire DOM.

Example:

<ol class="humans">
<li>Gandalf</li>
<li>Saruman</li>
<li>Aragorn</li>
<li>Boromir</li>
<li>Faramir</li>
</ol>
const humans = document.querySelector('.humans')
const firstHuman = humans.querySelector('li') // <li>Gandalf</li>

Summary

  • Use document.querySelector to select elements with CSS selectors.
  • querySelector returns the first match; use querySelectorAll for multiple elements.
  • Use element.querySelector to search within a specific element for better performance.