Home » Blog » Javascript Can Change HTML Content

Javascript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

This example uses the method to “find” an HTML element (with id=”line”) and changes the element content (innerHTML) to “Hello JavaScript”:

<html>

<body>
	<h2>Java Script Can Change HTML Content</h2>
	
	<p id="line">This Is HTML Content</p>
	<button type="button" onclick='document.getElementById("line").innerHTML = "The Content Is Changed By Javascript"'>Click Me to Change</button>
</body>

</html>

JavaScript accepts both double and single quotes:

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

<html>

<body>
	<h2>Java Script Can Change HTML Attribute</h2>
	<button type="button" onclick='document.getElementById("bulb").src = "off.gif"'>Off The Bulb</button>
	<img id="bulb" src="off.gif">
	<button type="button" onclick='document.getElementById("bulb").src = "on.gif"'>On The Bulb</button>
</body>

</html>

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

<html>

<body>
	<h2>Java Script Can Change Style</h2>
	
	<p id="line">This Is HTML Content</p>
	<button type="button" onclick='document.getElementById("line").style.fontSize = "35px"'>Click Me to Change</button>
</body>

</html>

Hide and Show HTML Content

Showing hidden HTML elements can also be done by changing the display style:

<html>

<body>
	<h2>Java Script Can Change HTML Attribute</h2>
	<button type="button" onclick='document.getElementById("line").style.display = "none"'>Hide Data</button>
	<p id="line">This Is HTML Content</p>
	<button type="button" onclick='document.getElementById("line").style.display = "block"'>Show Data</button>
</body>

</html>

 

Leave a Reply

Your email address will not be published.