JavaScript Code

How to get element by id using JavaScript?

Tutorials using JS

Problem Statement

find or get element by the attribute id from the document using JavaScript


to find and get an element by id attribute of the element, we can use document.getElementById() method. call getElementById() and pass the id value as string argument. the method returns an Element object, if the element is present with the specified id, or null if there is no such element



in the following program, we get the paragraph with id "myPara" and change its background color to LightGreen

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Hide all links in document</h2>
<button id="myBtn">Click me</button><br>
<div id="myDiv">A Div</div>
<p id="output"></p>

//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
	let myDiv = document.getElementById("myDiv"); = "LightGreen";


Copyright @2022