JavaScript Code

How to get element by id using JavaScript?

Tutorials using JS

Get element by id in JavaScript

In this tutorial, you have to 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