Selecting an Element By Id

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

let element = document.getElementById(id);Code language: JavaScript (javascript)

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>Code language: HTML, XML (xml)

JavaScript

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;
    }
});Code language: JavaScript (javascript)
Was this tutorial helpful ?