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

Solution

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

document.getElementById('myDiv')

Program

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

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

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
	let myDiv = document.getElementById("myDiv");
	myDiv.style.background = "LightGreen";
});
</script>

</body>
</html>

Copyright @2022