javascript-course

Changing a Web Page

JavaScript provides powerful tools for dynamically changing a web page’s content and behavior. This allows for interactive and engaging user experiences. Here are some ways to change a web page with JavaScript, along with examples:

1. Modifying HTML Content

<p id="message">This is the original message.</p>
// Get the element by ID
const messageElement = document.getElementById("message");

// Change the content
messageElement.innerHTML = "This is the new message.";
<div id="container"></div>
// Get the container element
const container = document.getElementById("container");

// Create a new element
const newElement = document.createElement("p");

// Set the element content
newElement.textContent = "This is a new paragraph.";

// Add the new element to the container
container.appendChild(newElement);

// Remove an element
container.removeChild(document.getElementById("childElement"));

2. Modifying CSS Styles

<h1 id="heading">Heading</h1>
const headingElement = document.getElementById("heading");
headingElement.style.color = "red";
headingElement.style.fontSize = "20px";
<button id="button">Click Me</button>
const buttonElement = document.getElementById("button");

// Add a class
buttonElement.classList.add("active");

// Remove a class
buttonElement.classList.remove("disabled");

3. Reacting to Events

<button id="button">Click Me</button>
const buttonElement = document.getElementById("button");

buttonElement.addEventListener("click", function () {
  alert("Button clicked!");
});

Examples:

<button id="button">Change Text</button>
const buttonElement = document.getElementById("button");

buttonElement.addEventListener("click", function () {
  buttonElement.textContent = "Text changed!";
});
<div id="element">This element will be hidden.</div>
window.addEventListener("scroll", function () {
  const element = document.getElementById("element");
  if (window.scrollY > 100) {
    element.style.display = "none";
  } else {
    element.style.display = "block";
  }
});

These are just a few basic examples of how to change a web page with JavaScript. With a bit of practice, you can create complex and dynamic web pages that respond to user interaction and update in real time.

Here are some resources for further learning:

Remember, the possibilities are endless when it comes to changing a web page with JavaScript. Be creative and have fun!