curriculum/challenges/english/blocks/review-dom-manipulation-and-click-events-with-javascript/6723cc7a8e7aa3b9befd4bac.md
html element. It's the top-level container for all the content of an HTML document. All other nodes are descendants of this root node. Then, below the root node, we find other nodes in the hierarchy. A parent node is an element that contains other elements. A child node is an element that is contained within another element.navigator Interface: This provides information about the browser environment, such as the user agent string, the platform, and the version of the browser. A user agent string is a text string that identifies the browser and operating system being used.window Interface: This represents the browser window that contains the DOM document. It provides methods and properties for interacting with the browser window, such as resizing the window, opening new windows, and navigating to different URLs.querySelector(), querySelectorAll() and getElementById() MethodsgetElementById() Method: This method is used to get an object that represents the HTML element with the specified id. Remember that ids must be unique in every HTML document, so this method will only return one Element object.:::interactive_editor
<div id="container"></div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container)
:::
querySelector() Method: This method is used to get the first element in the HTML document that matches the CSS selector passed as an argument.:::interactive_editor
<section class="section"></section>
<script src="./index.js"></script>
const section = document.querySelector(".section");
console.log(section)
:::
querySelectorAll() Method: You can use this method to get a list of all the DOM elements that match a specific CSS selector.:::interactive_editor
<ul class="ingredients">
<li>Sugar</li>
<li>Milk</li>
<li>Eggs</li>
</ul>
<script src="./index.js"></script>
const ingredients = document.querySelectorAll('ul.ingredients li');
console.log(ingredients)
:::
innerText(), innerHTML(), createElement() and textContent() MethodsinnerHTML Property: This is a property of the Element that is used to set or update parts of the HTML markup.:::interactive_editor
<div id="container">
<!-- Add new elements here -->
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
container.innerHTML = '<ul><li>Cheese</li><li>Tomato</li></ul>';
:::
createElement Method: This is used to create an HTML element.const img = document.createElement("img");
innerText: This represents the visible text content of the HTML element and its descendants.:::interactive_editor
<div id="container">
<p>Hello, World!</p>
<p>I'm learning JavaScript</p>
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container.innerText);
:::
textContent: This returns the plain text content of an element, including all the text within its descendants.:::interactive_editor
<div id="container">
<p>Hello, World!</p>
<p>I'm learning JavaScript</p>
</div>
<script src="./index.js"></script>
const container = document.getElementById("container");
console.log(container.textContent);
:::
appendChild() and removeChild() MethodsappendChild() Method: This method is used to add a node to the end of the list of children of a specified parent node.:::interactive_editor
<ul id="desserts">
<li>Cake</li>
<li>Pie</li>
</ul>
<script src="./index.js"></script>
const dessertsList = document.getElementById("desserts");
const listItem = document.createElement("li");
listItem.textContent = "Cookies";
dessertsList.appendChild(listItem);
:::
removeChild() Method: This method is used to remove a node from the DOM.:::interactive_editor
<section id="example-section">
<h2>Example sub heading</h2>
<p>first paragraph</p>
<p>second paragraph</p>
</section>
<script src="./index.js"></script>
const sectionEl = document.getElementById("example-section");
const lastParagraph = document.querySelector("#example-section p:last-of-type");
sectionEl.removeChild(lastParagraph);
:::
setAttribute() Method:::interactive_editor
<p id="para">I am a paragraph</p>
<script src="./index.js"></script>
const para = document.getElementById("para");
para.setAttribute("class", "my-class");
:::
Event object is a payload that triggers when a user interacts with your web page in some way. These interactions can be anything from clicking on a button or focusing an input to shaking their mobile device. All Event objects will have the type property. This property reveals the type of event that triggered the payload, such as keydown or click. These values will correspond to the same values you might pass to addEventListener(), where you can capture and utilize the Event object.addEventListener() and removeEventListener() MethodsaddEventListener Method: This method is used to listen for events. It takes two arguments: the event you want to listen for and a function that will be called when the event occurs. Some common examples of events would be click events, input events, and change events.:::interactive_editor
<button id="btn">Click Me</button>
<script src="./index.js"></script>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => alert("You clicked the button"));
:::
removeEventListener() Method: This method is used to remove an event listener that was previously added to an element using the addEventListener() method. This is useful when you want to stop listening for a particular event on an element.:::interactive_editor
<body>
<p id="para">Hover over me to disable the button's click event</p>
<button id="btn">Toggle Background Color</button>
</body>
<script src="./index.js"></script>
const bodyEl = document.querySelector("body");
const para = document.getElementById("para");
const btn = document.getElementById("btn");
let isBgColorGrey = true;
function toggleBgColor() {
bodyEl.style.backgroundColor = isBgColorGrey ? "blue" : "grey";
isBgColorGrey = !isBgColorGrey;
}
btn.addEventListener("click", toggleBgColor);
para.addEventListener("mouseover", () => {
btn.removeEventListener("click", toggleBgColor);
});
:::
addEventListener method instead.:::interactive_editor
<button onclick="alert('Hello World!')">Show alert</button>
:::
:::interactive_editor
<label>
Choose a programming language:
<select class="language" name="language">
<option value="">---Select One---</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="C++">C++</option>
</select>
</label>
<p class="result"></p>
<script src="./index.js"></script>
const selectEl = document.querySelector(".language");
const result = document.querySelector(".result");
selectEl.addEventListener("change", (e) => {
result.textContent = `You enjoy programming in ${e.target.value}.`;
});
:::
stopPropagation() Method: This method prevents further propagation for an event.DOMContentLoaded event is fired when everything in the HTML document has been loaded and parsed. If you have external stylesheets, or images, the DOMContentLoaded event will not wait for those to be loaded. It will only wait for the HTML to be loaded.style and classListElement.style Property: This property is a read-only property that represents the inline style of an element. You can use this property to get or set the style of an element.:::interactive_editor
<p id="para">This paragraph will turn red.</p>
<script src="./index.js"></script>
const paraEl = document.getElementById("para");
paraEl.style.color = "red";
:::
Element.classList Property: This property is a read-only property that can be used to add, remove, or toggle classes on an element.:::interactive_editor
<link rel="stylesheet" href="./styles.css"/>
<p id="para" class="blue-background">This paragraph will have classes added and removed.</p>
<div id="menu" class="menu">Menu Content</div>
<button id="toggle-btn">Toggle Menu</button>
<script src="./index.js"></script>
.highlight {
background-color: yellow;
}
.blue-background {
background-color: lightblue;
}
.menu {
display: none;
padding: 10px;
background-color: #f0f0f0;
}
.menu.show {
display: block;
}
// Example adding a class
const paraEl = document.getElementById("para");
paraEl.classList.add("highlight");
// Example removing a class
paraEl.classList.remove("blue-background");
// Example toggling a class
const menu = document.getElementById("menu");
const toggleBtn = document.getElementById("toggle-btn");
toggleBtn.addEventListener("click", () => menu.classList.toggle("show"));
:::
setTimeout() and setInterval() MethodssetTimeout() Method: This method lets you delay an action for a specified time.:::interactive_editor
setTimeout(() => {
console.log('This runs after 3 seconds');
}, 3000);
:::
setInterval() Method: This method keeps runs a piece of code repeatedly at a set interval. Since setInterval() keeps executing the provided function at the specified interval, you might want to stop it. For this, you have to use the clearInterval() method.:::interactive_editor
setInterval(() => {
console.log('This runs every 2 seconds');
}, 2000);
// Example using clearInterval
const intervalID = setInterval(() => {
console.log('This will stop after 5 seconds');
}, 1000);
setTimeout(() => {
clearInterval(intervalID);
}, 5000);
:::
requestAnimationFrame() Methodfunction animate() {
// Update the animation...
// for example, move an element, change a style, and more.
update();
// Request the next frame
requestAnimationFrame(animate);
}
:::interactive_editor
<link rel="stylesheet" href="./styles.css"/>
<div id="square"></div>
<script src="./index.js"></script>
#square {
width: 100px;
height: 100px;
background: red;
}
const square = document.querySelector('#square');
const animation = square.animate(
[{ transform: 'translateX(0px)' }, { transform: 'translateX(100px)' }],
{
duration: 2000, // makes animation lasts 2 seconds
iterations: Infinity, // loops indefinitely
direction: 'alternate', // moves back and forth
easing: 'ease-in-out', // smooth easing
}
);
:::
canvas element in HTML. This element acts as a drawing surface you can manipulate with the instance methods and properties of the interfaces in the Canvas API. This API has interfaces like HTMLCanvasElement, CanvasRenderingContext2D, CanvasGradient, CanvasPattern, and TextMetrics which contain methods and properties you can use to create graphics in your JavaScript file.:::interactive_editor
<canvas id="my-canvas" width="400" height="400"></canvas>
<script src="./index.js"></script>
const canvas = document.getElementById('my-canvas');
// Access the drawing context of the canvas.
// "2d" allows you to draw in two dimensions
const ctx = canvas.getContext('2d');
// Set the background color
ctx.fillStyle = 'crimson';
// Draw a rectangle
ctx.fillRect(1, 1, 150, 100);
:::
showModal() Method: This method is used to open a modal.:::interactive_editor
<dialog id="my-modal">
<p>This is a modal dialog.</p>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
<script src="./index.js"></script>
const dialog = document.getElementById('my-modal');
const openButton = document.getElementById('open-modal');
openButton.addEventListener('click', () => {
dialog.showModal();
});
:::
close() Method: This method is used to close the modal.:::interactive_editor
<dialog id="my-modal">
<p>This is a modal dialog.</p>
<button id="close-modal">Close Modal</button>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
<script src="./index.js"></script>
const dialog = document.getElementById('my-modal');
const openButton = document.getElementById('open-modal');
const closeButton = document.getElementById('close-modal');
openButton.addEventListener('click', () => {
dialog.show();
});
closeButton.addEventListener('click', () => {
dialog.close();
});
:::
Review the DOM Manipulation and Click Events with JavaScript topics and concepts.