Introduction :
You can add one piece of JavaScript code with a HTML page to change or modify HTML and CSS values dynamically. HTML is a markup language that is used to define the structure of a page, CSS is style rules used to add styles to a HTML page and JavaScript is a scripting programming language that is used to add complex dynamic features to a HTML page like responding to different user interactions, changing the web page dynamically, animate the page, etc. Without JavaScript, your web page will be a static page.
Changing HTML page content :
To change one part of a HTML page dynamically, the JavaScript code should get access to these elements. For that, each web browser provides one API called DOM or Document Object Model API. Using this API, we can dynamically change the HTML or css part of a web page.
Inside a JavaScript code, we can access an HTML element using a document object. This object is available by default and you don’t have to create it. It provides different methods to access and modify HTML components. Following are the most commonly used DOM APIs :
- document.getElementById("id");
- document.getElementsByTagName("tag");
- document.createElement(<type>);
getElementById finds and returns one object using the provided id. Similarly, getElementsByTagName gets one element using a tag and createElement creates one element.
All of these methods return one object that can be hold in a JavaScript variable. We can get the content of an element by using innerHTML property.
These are common methods. We have a lot more different methods to change and manipulate each element we got.
JavaScript program to change HTML page :
Let’s consider the below program :
<!DOCTYPE html>
<html>
<body>
<p id="content">Default Content</p>
<button id="button" type="button">Click Here</button>
</body>
<script>
function changeContent() {
document.getElementById("content").innerHTML = "Hello World!";
}
document.getElementById("button").onclick = function () {
changeContent();
};
</script>
</html>
Create one html file index.html, copy-paste these code and open that file in a browser. It will show one button ‘Click Here’ and one text ‘Default Content’. If you click on the button, it will change the text to ‘Hello World!’.
Explanation :
- The id of the text that we need to change is content. The id of the button is ‘button’.
- The JavaScript part is written inside the script tags. Once we click on the button, it calls the function ‘changeContent’.
- This function gets the text by the id ‘content’ and changes its content using ‘innerHTML’ property to ‘Hello World!’.