• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / CSS / Selecting an Element By Id

Selecting an Element By Id

Selecting an Element By Id

Select an element that matches the id using the getElementById() method.

To get an element by id, you use the getElementById() method of the Document object:

let element = document.getElementById(id);

The method returns an element whose id matches a specified string. 

The id is case-sensitive. If no matching element was found, the method returns null.

Since the id is supposed to be unique, using the getElementById() method is a fast way to select an element.

If the element does not have an ID, you can use the querySelector() to find the element using any CSS selector.

See the following example:

<html>
<head>
  <title>JavaScript getElementById() example</title>
</head>
<body>
  <h1 id="message">JavaScript getElementById() Demo</h1>
  <div id="btn">
    <button id="btnRed">Red</button>
    <button id="btnGreen">Green</button>
    <button id="btnBlue">Blue</button>
  </div>
  <script src="js/app.js"></script>
</body>
</html>
const changeColor = (newColor) => {
    const element = document.getElementById('message');
    element.style.color = newColor;
}

let div = document.getElementById('btn');

div.addEventListener('click', (event) => {
    let target = event.target;
    switch (target.id) {
        case 'btnRed':
            changeColor('red');
            break;
        case 'btnGreen':
            changeColor('green  ');
            break;
        case 'btnBlue':
            changeColor('blue');
            break;
    }
});

Source

  • https://www.javascripttutorial.net/dom/selecting/selecting-an-element-by-id/

CSS

Related Snippets:

  • Selecting Elements By Class Name
  • Apply a CSS animation to an element with JavaScript
  • Retrieve the value of a CSS rule for the specified element
  • Get the Children of an Element

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers