Skip to content

Instantly share code, notes, and snippets.

@guillaumecabanel
Last active February 17, 2021 08:32
Show Gist options
  • Save guillaumecabanel/46061847305d1a41bf9ec4cc86b348bc to your computer and use it in GitHub Desktop.
Save guillaumecabanel/46061847305d1a41bf9ec4cc86b348bc to your computer and use it in GitHub Desktop.

CSS SELECTOR CHEAT SHEET

source :

Simple selector

  <ul>
    <li>Alice</li>
    <li>Bob</li>
    <li>Charlie</li>
    <li>Eve</li>
  </ul>
document.querySelector('ul li:first-child').innerText  // Alice
document.querySelector('ul li:nth-child(2)').innerText // Bob
document.querySelector('ul li:last-child').innerText // Eve

Multiple selector

  <ul>
    <li>Alice</li>
    <li>Bob</li>
    <li>Charlie</li>
    <li>Eve</li>
  </ul>

  <ul>
    <li>Cecile</li>
    <li>Nicolas</li>
    <li>Guillaume</li>
    <li>Tim</li>
  </ul>
document.querySelectorAll('ul li:first-child');  // Alice and Cecile
document.querySelectorAll('ul li:nth-child(2)'); // Bob and Nicolas
document.querySelectorAll('ul li:last-child');   // Eve and Tim

document.querySelector('body ul:last-child li:first-child') // Cecile
ul li:first-child {
  color: #FF0000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment