The Web Dev Guide by Wishtack
  • The Web Dev Guide by Wishtack
  • HTML
    • HTML Tags
    • HTML Attributes
    • Content Formatting
    • Empty Tags vs Content Tags
    • Some Links
  • ECMAScript
    • Some History
    • Language Properties
    • Single-Threaded thus Asynchronous
    • The Event Loop
    • Classes
    • Hoisting is Dead: var vs. let vs. const
    • this & "binding"
    • Arrow Functions
    • Template Strings
    • Syntactic Sugar
      • Spread
      • Destructuring
      • Rest
      • Object Literal Property Value Shorthand
    • Named Parameters
    • Compatibility
  • Tools
    • Node.js
    • NPM
    • Yarn
    • Webpack
    • WebStorm
    • StackBlitz
  • DOM
    • What Is It?
    • Element Selection
    • Element Modification
    • Events
  • Forms
    • The <form> tag
    • Form elements
    • Form validation
  • Networking
    • Fetch Web API
  • CSS
    • Selectors
    • Transforms
    • Transitions
    • Animations
    • Web Animations API
    • Sass
  • Responsive Web Design
    • Viewport
    • Media Queries
    • Grid Layout
    • Flex Layout
    • Frameworks & Libraries
  • Web APIs
  • Testing
    • Unit Testing
    • End to End Testing
  • Security
    • Injection
    • DOM XSS
    • Insecure Direct Object Reference
    • Cross-Site Request Forgery
    • Client vs API Validation
    • API Unauthorized Access and Data Leak
  • More Links
Powered by GitBook
On this page
  • Old School
  • Selecting an element by id
  • Select using CSS class
  • Select by HTML tag
  • Modern Way
  • Select using query selector
  1. DOM

Element Selection

Old School

Selecting an element by id

document.getElementById('login');

This code will return the first element having the given id.

<input id="login">

Select using CSS class

document.getElementsByClassName('blog-post');

This code will return the first element having the blog-post-content CSS class.

<section class="blog-post-content"></section>

Select by HTML tag

document.getElementsByTagName('header')

This code will return the first element having the header HTML tag.

<header>This is the header.</header>

Modern Way

Select using query selector

document.querySelector('header');
document.querySelectorAll('div.blog-post-content');

The first call will return the first element with the header HTML tag.

The second call will return an iterable object with all the items with a div HTML tag and the blog-post-content CSS class.

This is the easier and most modern way of selecting elements.

querySelector and querySelectorAll methods are also available on every element in order to search for child elements.

const firstNameInput = form.querySelector('input[name="firstName"]');
PreviousWhat Is It?NextElement Modification

Last updated 6 years ago