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.

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