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

Syntax

The syntax of getElementById() function is

document.getElementById("id_value");

where

  • 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

Examples

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>
<html>
<body>
<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>

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

</body>
</html>


Copyright @2022