JavaScript

JavaScript Comprehensive Guide: From Basics to DOM Manipulation

JavaScript is the world's most popular programming language. It is the language of the Web—used for HTML, servers, PCs, laptops, tablets, and phones (Mozilla, 2024a). This guide will take you from the fundamental syntax to manipulating the HTML Document Object Model (DOM).


Part 1: JavaScript Basics

What is JavaScript?

JavaScript is a sequence of statements to be executed by the browser. It can change HTML content, attributes, and styles. You can write JavaScript directly inside an HTML document using the <script> tag (Mozilla, 2024a).

<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>

Variables and Data Types

JavaScript variables are containers for storing data values. Variables are declared using the var, let, or const keywords (Mozilla, 2024b).

  • Data Types: String (text), Number, Boolean (true/false), Array, Object, Null, Undefined.
  • Dynamic Typing: The same variable can hold different data types over time.
var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

// Arrays
var cars = ["Saab", "Volvo", "BMW"]; // Literal array

// Objects
var person = {
  firstname: "John",
  lastname: "Doe",
  age: 50
};

Functions

A function is a block of code designed to perform a particular task. It is executed when "something" invokes (calls) it (Mozilla, 2024b).

function myFunction(name, job) {
  alert("Welcome " + name + ", the " + job);
}

// Call the function
myFunction("Harry Potter", "Wizard");

// Function with a return value
function sum(a, b) {
  return a + b;
}
var total = sum(5, 10); // total is 15

Operators & Conditional Statements

JavaScript includes arithmetic operators (+ - * / %), assignment operators (= += -=), and comparison operators (== === != !== > <).

var age = 20;

if (age < 18) {
  document.write("Too young to vote");
} else if (age === 18) {
  document.write("You can vote for the first time!");
} else {
  document.write("You can vote.");
}

Loops

Loops execute a block of code a number of times (Mozilla, 2024b).

// For Loop
for (var i = 0; i < 5; i++) {
  document.write("The number is " + i + "<br>");
}

// While Loop
var i = 0;
while (i < 5) {
  document.write("The number is " + i + "<br>");
  i++;
}

// For/In Loop (iterates through object properties)
var person = {fname:"John", lname:"Doe", age:25};
for (var x in person) {
  document.write(person[x] + "<br>");
}

Part 2: The HTML DOM (Document Object Model)

The HTML DOM is a standard object model and programming interface for HTML. It allows JavaScript to access and manipulate all elements of an HTML document (W3C, 2023).

Finding HTML Elements

To manipulate an HTML element, you first need to find it. The most common methods are (Mozilla, 2024c):

  • document.getElementById(id) - Finds an element by its ID.
  • document.getElementsByTagName(name) - Finds elements by their tag (e.g., "p").
  • document.getElementsByClassName(name) - Finds elements by their class name.
<p id="demo">Hello World!</p>
<script>
  var x = document.getElementById("demo");
  document.write("The text is: " + x.innerHTML);
</script>

Changing HTML Content, Attributes, and CSS

  • Content: document.getElementById(id).innerHTML = new HTML
  • Attribute: document.getElementById(id).attribute = new value
  • Style: document.getElementById(id).style.property = new style
<p id="p1">Hello World!</p>
<img id="myImg" src="pic1.jpg">

<script>
  // Change Content
  document.getElementById("p1").innerHTML = "New text!";
  
  // Change CSS
  document.getElementById("p1").style.color = "blue";
  document.getElementById("p1").style.fontSize = "20px";
  
  // Change Attribute
  document.getElementById("myImg").src = "pic2.jpg";
</script>

Adding and Removing Elements (Nodes)

To add a new element to the DOM, you must create the element, create the text, append the text to the element, and finally append the element to an existing container (Mozilla, 2024c).

<div id="div1">
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
  // Create new element
  var para = document.createElement("p");
  var node = document.createTextNode("This is new.");
  para.appendChild(node);
  
  // Append to existing element
  var element = document.getElementById("div1");
  element.appendChild(para);
  
  // Remove element
  var child = document.getElementById("p1");
  child.parentNode.removeChild(child);
</script>

Part 3: JavaScript Events

Events are actions that happen in the browser, such as when a user clicks a button, the page loads, or an input field changes (Mozilla, 2024d).

Common HTML Events

  • onclick - When the user clicks an element.
  • onmouseover / onmouseout - When the mouse hovers over or leaves an element.
  • onchange - When an input field is changed (often used for validation).
  • onload / onunload - When the page is loaded or closed.
<!-- Inline Event Handler -->
<button onclick="document.getElementById('demo').innerHTML = Date()">Show Date</button>

<!-- Changing Text on Hover -->
<p onmouseover="this.style.color='red'" onmouseout="this.style.color='black'">
  Hover over me!
</p>

<!-- Validating Input on Change -->
<input type="text" id="fname" onchange="myFunction()">
<script>
function myFunction() {
  var x = document.getElementById("fname");
  x.value = x.value.toUpperCase();
}
</script>

Part 4: Advanced JavaScript Objects & BOM

The Math Object

The Math object allows you to perform mathematical tasks without creating an object (Mozilla, 2024e).

Math.round(2.5);     // 3
Math.max(5, 10);     // 10
Math.floor(Math.random() * 11); // Random number between 0 and 10

Regular Expressions (RegExp)

A regular expression is a sequence of characters that forms a search pattern. It is used for pattern-matching and "search-and-replace" functions on text (Mozilla, 2024e).

var str = "Visit W3Schools";
var patt1 = /w3schools/i; // 'i' makes it case-insensitive
var result = str.match(patt1);

// Using test() returns true or false
var patt2 = /e/;
patt2.test("The best things in life are free"); // true

The Browser Object Model (BOM)

The BOM allows JavaScript to "talk to" the browser. The window object represents the browser window (Mozilla, 2024f).

  • Window Size: window.innerHeight and window.innerWidth.
  • Window Location: window.location.href returns the current page URL.
  • Window History: window.history.back() acts like clicking the back button.
  • Popup Boxes: alert() (message), confirm() (OK/Cancel), prompt() (input).
// Redirect the browser
function newDoc() {
  window.location.assign("https://www.example.com");
}

// Confirmation Box
function myConfirm() {
  var r = confirm("Press a button!");
  if (r == true) {
    document.write("You pressed OK!");
  } else {
    document.write("You pressed Cancel!");
  }
}

Timing Events

JavaScript can execute code at specified time intervals (Mozilla, 2024f).

  • setInterval() - Executes a function over and over again at a set interval.
  • setTimeout() - Executes a function once after waiting a set number of milliseconds.
// Alert "Hello" after 3 seconds (3000 milliseconds)
setTimeout(function(){ alert("Hello"); }, 3000);

// Update a clock every second
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
  var d = new Date();
  document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

JavaScript Cookies

Cookies are small text files stored on the user's computer. They are used to remember information about the user (like a username) between visits (Mozilla, 2024g).

function setCookie(c_name, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
  var c_value = document.cookie;
  var c_start = c_value.indexOf(" " + c_name + "=");
  if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); }
  if (c_start == -1) { c_value = null; } 
  else {
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
    if (c_end == -1) { c_end = c_value.length; }
    c_value = unescape(c_value.substring(c_start, c_end));
  }
  return c_value;
}

Part 5: JavaScript Libraries & Frameworks

Modern JavaScript development relies heavily on libraries to handle complex tasks like DOM manipulation and AJAX (Mozilla, 2024a).

  • jQuery: The most popular framework. It uses CSS selectors to access and manipulate HTML elements. It makes tasks like animations and event handling much simpler.
  • Prototype: A library that enhances JavaScript by providing classes and inheritance. It includes an Event.observe() method to handle events.
  • MooTools: A framework that offers an API for common JavaScript tasks, including lightweight effects and animations.

Using a CDN (Content Delivery Network)
Instead of downloading a library, you can link directly to a shared version hosted on a CDN like Google. This speeds up page load times because the browser may have already cached the library from another site.

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

Conclusion: Mastering JavaScript is essential for modern web development. By understanding the core syntax, the HTML DOM, and how to handle events, you can build dynamic, interactive web applications. From there, leveraging libraries like jQuery can significantly speed up your development process (Mozilla, 2024a).


References

Mozilla. (2024a). JavaScript. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript

Mozilla. (2024b). JavaScript guide: Grammar and types. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types

Mozilla. (2024c). Document Object Model (DOM). MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

Mozilla. (2024d). Introduction to events. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Mozilla. (2024e). Standard built-in objects. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

Mozilla. (2024f). Window. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Window

Mozilla. (2024g). Document.cookie. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

W3C. (2023). DOM Standard. W3C. https://dom.spec.whatwg.org/

10 comments:

  1. Authentic content..very knowledgeable.. thanks for this post.
    Tally on Cloud Server
    Tally on AWS

    ReplyDelete