java script and dom manipulation

๐Ÿ’ช JavaScript: Powering Dynamic Websites

๐Ÿ’ก Notice: JavaScript makes websites interactive. This example runs JavaScript only โ€” HTML & CSS examples need structure to display visuals. If you havenโ€™t studied HTML yet, visit our HTML5 Lesson.

JavaScript is the powerhouse behind interactive and dynamic websites. Whether it's animating a button, updating content dynamically, or creating entire web applications, JavaScript has your back. ๐Ÿ’ช

๐Ÿ› ๏ธ JavaScript Basics: Variables, Data Types, Operators, and Functions

JavaScript is a versatile, high-level programming language used to control the behavior of web pages. When combined with HTML and CSS, it enables web developers to build interactive and responsive websites.

Think of it as the brain ๐Ÿง  of your website, while HTML is the skeleton and CSS is the skin and makeup.

๐Ÿ—‚๏ธ Variables: Storing Information

Variables act like containers that hold data values.


// Declaring Variables
let playerName = "Eddy"; // Can change
const MAX_LEVEL = 10;    // Constant value
var score = 0;           // Avoid using var in modern JS

๐Ÿ—๏ธ Data Types: Understanding JavaScript's Building Blocks


// Primitive Data Types
let greeting = "Hello, World!";
let age = 25;
let pi = 3.14;
let isRaining = false;
let emptyValue = null;
let notAssigned;

// Non-Primitive Data Types
let user = { name: "Eddy", age: 25, role: "Developer" };
let colors = ["red", "blue", "green"];

โž• Operators: Performing Actions

Operators are special symbols that perform actions on values or variables.


let a = 10, b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0

โœ๏ธ Assignment Operators


let x = 10;
x += 5; // 15
x *= 2; // 30

๐Ÿง Comparison Operators


let a = 5;
let b = "5";
console.log(a == b);  // true
console.log(a === b); // false
console.log(10 > 5);  // true

๐Ÿค Logical Operators


let isAdult = true;
let hasID = false;
console.log(isAdult && hasID); // false
console.log(isAdult || hasID); // true
console.log(!isAdult);         // false

๐Ÿงต String Operators


let greeting = "Hello";
greeting += ", World!";
console.log(greeting); // Hello, World!

๐Ÿ” Type & Special Operators


console.log(typeof "Hello"); // string
console.log([] instanceof Array); // true

let x = (2, 3); // x is 3
console.log(x);

let name = null;
let defaultName = name ?? "Guest";
console.log(defaultName); // Guest

๐Ÿง  Understanding JavaScript Functions

Functions make your code reusable and easier to maintain. Below, you can edit the example and click Run to see it in action!

โš ๏ธ Note: CSS code wonโ€™t display on its own โ€” always include some HTML to see the visual results (as learned in our HTML5 Class). If you havenโ€™t covered that yet, check our HTML5 guide on our web platform.

๐Ÿ’ป Try It Yourself

Edit the code below and click Run to see how functions work.

๐ŸŒ€ JavaScript Loops โ€“ Complete Lesson

Loops are one of the most powerful tools in JavaScript. They allow us to execute a block of code repeatedly, saving time and effort. Imagine you need to print numbers from 1 to 100โ€”doing it manually would be exhausting! Loops let you automate this process, making your code efficient and concise.

So, buckle up as we explore loops in JavaScript, step by step, with plenty of examples to make learning fun! ๐Ÿš€

Why Use Loops?

Types of Loops in JavaScript ๐ŸŒ€

for loop, while loop, do...while loop, for...in loop, for...of loop

1๏ธโƒฃ For Loop ๐Ÿงฎ

The for loop repeats a block of code a specific number of times.

Syntax:

for (initialization; condition; increment/decrement) { /* code */ }

Example: Counting from 1 to 5

for (let i = 1; i <= 5; i++) {
  console.log(`Count: ${i}`);
}

2๏ธโƒฃ While Loop โ™ป๏ธ

Continues as long as the specified condition is true.

Example: Printing numbers until 5

let num = 1;
while (num <= 5) {
  console.log(`Number: ${num}`);
  num++;
}

3๏ธโƒฃ Do...While Loop ๐Ÿ”„

Runs at least once, then repeats while the condition is true.

Example:

let count = 6;
do {
  console.log(`Count: ${count}`);
  count++;
} while(count <= 5);

4๏ธโƒฃ For...In Loop ๐Ÿ”

Used to iterate over object properties.

Example:

const person = { name: "Eddy", age: 25, role: "Instructor" };
for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

5๏ธโƒฃ For...Of Loop ๐ŸŒŸ

Used to iterate over arrays or strings.

Example:

const fruits = ["๐ŸŽ", "๐ŸŒ", "๐Ÿ“"];
for (let fruit of fruits) {
  console.log(`I love ${fruit}`);
}

6๏ธโƒฃ Special Keywords ๐Ÿšฆ

break: Exits the loop entirely.

continue: Skips the current iteration and moves to the next.

Example:

for (let i = 1; i <= 5; i++) {
  if(i===3) continue;
  if(i===5) break;
  console.log(i);
}

7๏ธโƒฃ Nested Loops ๐Ÿ”—

Loops inside loops for multi-level tasks like multiplication tables.

Example:

for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(`${i} x ${j} = ${i*j}`);
  }
}

Looping Through Strings and Arrays

String Example:

const name = "Eddy";
for(let char of name){
  console.log(char);
}

Array Example:

const numbers = [10,20,30];
for(let num of numbers){
  console.log(num);
}

Infinite Loops ๐Ÿšจ

If the loop condition never becomes false, the loop runs forever. Be cautious!

Tips for Using Loops

๐ŸŒณ JavaScript DOM โ€“ Complete Lesson

The Document Object Model (DOM) is the foundation of every modern web page. It allows JavaScript to interact with HTML and CSS dynamically. In this guide, weโ€™ll explore what the DOM is, how to select elements, and how to manipulate them to create interactive websites. ๐ŸŽ‰

What is the DOM?

The DOM represents an HTML document as a tree of objects. These nodes can be:

Think of the DOM as a bridge between HTML and JavaScript. With JS, you can select elements, modify content or styles, and respond to user interactions.

Visualizing the DOM ๐ŸŒณ

Example HTML:

<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Welcome</h1>
    <p>Hello, World!</p>
    <button>Click Me</button>
  </body>
</html>

DOM Tree:

Selecting Elements in the DOM ๐ŸŽฏ

By ID

Use document.getElementById("id") to select a single element.

<h1 id="title">Hello, DOM!</h1>
<script>
  const title = document.getElementById("title");
  console.log(title.textContent); // Hello, DOM!
</script>

By Class

Use document.getElementsByClassName("className").

<p class="intro">Welcome!</p>
<p class="intro">Let's learn the DOM.</p>
<script>
  const intros = document.getElementsByClassName("intro");
  console.log(intros[0].textContent); // Welcome!
</script>

By Tag Name

Use document.getElementsByTagName("tagName").

<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
  const paragraphs = document.getElementsByTagName("p");
  console.log(paragraphs.length); // 2
</script>

Query Selectors

Modern and versatile methods:

document.querySelector("selector"); // first match
document.querySelectorAll("selector"); // all matches (NodeList)

Example:

<p id="info" class="highlight">Hello!</p>
<script>
  const info = document.querySelector("#info");
  console.log(info.textContent); // Hello!
</script>
<p class="highlight">One</p>
<p class="highlight">Two</p>
<script>
  const highlights = document.querySelectorAll(".highlight");
  highlights.forEach(el => console.log(el.textContent)); // One, Two
</script>

Modifying HTML Elements ๐Ÿ› ๏ธ

Change Text Content

<h1 id="title">Old Title</h1>
<script>
  const title = document.getElementById("title");
  title.textContent = "New Title";
</script>

Change HTML Structure

<div id="container"></div>
<script>
  const container = document.getElementById("container");
  container.innerHTML = "<p>Dynamic Content</p>";
</script>

Add / Modify Attributes

<img id="image" src="placeholder.jpg">
<script>
  const image = document.getElementById("image");
  image.setAttribute("src", "new-image.jpg");
</script>

Change Styles ๐ŸŽจ

<p id="text">Style Me!</p>
<script>
  const text = document.getElementById("text");
  text.style.color = "blue";
  text.style.fontSize = "20px";
</script>

Adding / Removing Classes

<p id="text" class="highlight">Styled Text</p>
<script>
  const text = document.getElementById("text");
  text.classList.add("bold");
  text.classList.remove("highlight");
</script>

Interactive Examples ๐ŸŽฎ

Change Text on Button Click

<p id="message">Click the button to change me!</p>
<button id="btn">Click Me</button>
<script>
  const button = document.getElementById("btn");
  const message = document.getElementById("message");
  button.addEventListener("click", () => {
    message.textContent = "You clicked the button!";
  });
</script>

Create New Elements Dynamically

<ul id="list"></ul>
<button id="add">Add Item</button>
<script>
  const list = document.getElementById("list");
  const addButton = document.getElementById("add");
  addButton.addEventListener("click", () => {
    const newItem = document.createElement("li");
    newItem.textContent = "New Item";
    list.appendChild(newItem);
  });
</script>

Exploring DOM Events ๐ŸŽ†

Events are actions that occur on a webpage, such as clicks, keypresses, or mouse movements.

Example: Listening for a Click Event

<button id="alert">Show Alert</button>
<script>
  const alertButton = document.getElementById("alert");
  alertButton.addEventListener("click", () => {
    alert("Button clicked!");
  });
</script>

By mastering the DOM, you can create dynamic, interactive, and user-friendly websites. Happy coding! ๐ŸŽ‰

๐Ÿ“š Additional Resources: JavaScript & DOM

Hereโ€™s a curated list of websites, videos, and tutorials to help you learn JavaScript and DOM manipulation in-depth. These resources cater to beginners and intermediate learners while providing hands-on experience.

Websites ๐ŸŒ

Videos ๐ŸŽฅ

AI Prompts for Further Learning ๐Ÿค–

You can use AI to explore more about JavaScript and DOM. Examples:

Basic Understanding

"Explain DOM manipulation with examples."
"What are the differences between querySelector and getElementById in JavaScript?"

Specific Use Cases

"Write a JavaScript script to create and delete elements dynamically in the DOM."
"How can I handle form validation errors in real-time using JavaScript?"

Advanced Concepts

"Explain the event propagation model (bubbling and capturing) with code examples."
"What are the best practices for handling large numbers of DOM elements?"

Debugging Assistance

"Why is my JavaScript click event listener not working on dynamically added elements?"
"How can I improve the performance of my DOM manipulation script?"