JavaScript Code

JavaScript – Find Element by ID

Tutorials using JS

Find Element by ID

to find an element in the document using id attribute, use Document.getElementById() function


The syntax of getElementById() function is



  • document object is the root node of the HTML document
  • getElementById is the function name
  • id_value is the value of the id which is used for searching the document


1. find element whose id is myPara

in the following document, we have two paragraphs, of which one has an id of 'myPara'. when user clicks on Click Me button, we find the element by id 'myPara' and change its background color

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Find Element by ID</h2>
<button id="myBtn">Click Me</button>
<p id="myPara">This is a paragraph.</p>
<p>This is another paragraph.</p>

//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //create list-item
    const myPara = document.getElementById('myPara'); = 'yellow';


Copyright @2022