Goal of the tutorial: The main goal of this tutorial is to teach you how to handle dynamic content on your webpages using JavaScript. Dynamic content refers to web content that changes based on user input, time, or any other factors.
Learning outcomes: By the end of this tutorial, you will know how to modify HTML elements, change CSS styles, and create new HTML elements dynamically using JavaScript.
Prerequisites: Basic knowledge of HTML, CSS, and JavaScript is required to follow along with this tutorial.
2. Step-by-Step Guide
JavaScript has the ability to manipulate the Document Object Model (DOM) of a webpage. The DOM represents the structure of HTML documents, allowing JavaScript to interact with and manipulate HTML elements dynamically.
JavaScript can modify HTML elements in several ways, including changing the content of an element, altering its CSS style, or even creating and removing elements altogether.
Example
Here's a simple example of how JavaScript can modify the content of an HTML element:
In this line of code, document.getElementById("demo") is used to select an HTML element with the id "demo". .innerHTML is then used to change the content of this element to "Hello, World!".
3. Code Examples
Example 1: Changing the content of an HTML element
<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a paragraph.</p>
<button onclick="changeContent()">Change Content</button>
<script>
function changeContent() {
document.getElementById("demo").innerHTML = "Content changed!";
}
</script>
</body>
</html>
In this example, clicking the button will change the content of the paragraph with id "demo" to "Content changed!".
Example 2: Altering the CSS style of an HTML element
<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a paragraph.</p>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
document.getElementById("demo").style.color = "red";
}
</script>
</body>
</html>
In this example, clicking the button will change the color of the text in the paragraph with id "demo" to red.
Example 3: Creating a new HTML element
<!DOCTYPE html>
<html>
<body>
<button onclick="createPara()">Create Paragraph</button>
<script>
function createPara() {
let para = document.createElement("p");
let node = document.createTextNode("This is a new paragraph.");
para.appendChild(node);
let element = document.getElementById("div1");
element.appendChild(para);
}
</script>
</body>
</html>
In this example, clicking the button will create a new paragraph element and append it to the body of the HTML document.
4. Summary
We have learned how to handle dynamic content in a webpage using JavaScript.
We learned how to modify the content of HTML elements, change their CSS styles, and create new elements dynamically.
Next steps: Practice what you've learned with different HTML elements and CSS styles. Experiment with creating and removing elements.