How To Use document.getElementById() Method In Javascript

Javascript uses various method to manage the validation and programming of a web page i.e. how to handle a web page is done by using Javascript. Javascript can change the HTML Content using the getElementById() method. Here we are explaining the usage of getElementById() method in Javascript. How to use this Javascript method to change HTML content on the web page.

Example:

<html>
<body> 

<p id="jsdemo">How To Use JavaScript method getElementById()</p> 
<button type="button" onclick='document.getElementById("jsdemo").innerHTML=
"JavaScript Method Run Successfully"'>Click</button>

</body> 
</html>

Note: onclick is the click event i.e. when user click on the button element then it triggers/executes the Javascript Method ‘getElementById()’.

Copy paste the above code in Notepad and save it as “demo.html”, then open this HTML file to check usage of getElementById() method.

Note: Javascript allows both single and double quotes.

1.document.getElementById("jsdemo").innerHTML = "JavaScript Method Run Successfully"

2.document.getElementById("jsdemo").innerHTML = 'JavaScript Method Run Successfully'

Javascript can change HTML Attribute values e.g. <img src=”example.jpg”></img> Javascript can change the “src” attribute value of HTML element “<img>” dynamically.

Example:

<html>
<body>

<p>JavaScript can change HTML attribute values.</p>

<p>In this example, JavaScript changes the value of the src (source) 
attribute of anHTML Image Element</p>

<img id="demoImage" src="red-flower.jpg">

<button onclick='document.getElementById('demoImage').src="yellow-flower.jpg"'>
Change flower's Color</button>

</body>
</html>

Javascript can also change the HTML Styles / CSS values. e.g. we can change font-size, width etc.  dynamically using the Javascript method “getElementById()”.

Example:

<html>
<body>

<p id="demo" style="font-size:20px">In this example, JavaScript changes 
the css style attribute "font-size" value </p>

<button onclick='document.getElementById('demo').style.fontSize="30px"'>Change flower's color</button>

</body>
</html>

You can also show or hide any HTML element by changing the values of “display” attribute of stylesheet css for any HTML element and it is also dynamically by using getElementById() method in Javascript. It is enough to understand ‘How To Use document.getElementById() Method In Javascript’.

References: Javascript Wiki

Leave a Reply

Your email address will not be published. Required fields are marked *