JavaScript Core Concepts and DOM Programming Guide

Wrapper Classes

JavaScript provides three wrapper classes: String, Boolean, and Number. These allow creation of object representations for primitive values.

let numericValue = new Number(42);
let textContent = new String("greetings");
let flagValue = new Boolean(true);

However, using wrapper classes in practice is strongly discouraged. When accessing properties or methods on primitive values, JavaScript temporarily converts the primitive to its corresponding wrapper object, performs the operation, then destroys the temporary object. This automatic conversion handles all use cases without manual wrapper instantiation.

String Methods and Operations

In JavaScript, strings are internally stored as character arrays.

Core String Methods

// Length access
let message = "Hello World";
console.log(message.length);  // 11
console.log(message[6]);      // "W"

// Character extraction
message.charAt(0);           // "H"
message.charCodeAt(0);       // 72 (Unicode value)
String.fromCharCode(65);     // "A"

// String concatenation
message.concat(" ", "From JS");  // "Hello World From JS"
// Or simply use the + operator
message + " Continue";           // "Hello World Continue"

Search and Position Methods

let sampleText = "JavaScript is powerful and versatile";

// Forward search from beginning
sampleText.indexOf("is");           // 11 (first occurrence)
sampleText.indexOf("is", 12);       // Search starting from position 12

// Backward search from end
sampleText.lastIndexOf("is");      // 19 (last occurrence)

Both methods return -1 when the search term is not found. The optional second parameter specifies the starting position.

Substring Extraction

let extractText = "Extract this portion";

// slice(start, end) - end is exclusive
extractText.slice(0, 7);           // "Extract"
extractText.slice(8);              // "this portion" (to end)
extractText.slice(-7);             // "portion" (negative counts from end)

// substring(start, end) - similar but cannot accept negative values
extractText.substring(0, 7);       // "Extract"
extractText.substring(7, 0);       // Automatically swaps: "Extract"

// substr(start, count) - second parameter is length, not position
extractText.substr(0, 7);          // "Extract"
extractText.substr(8, 4);          // "this"

Case Transformation

let mixedCase = "HeLLo WoRLd";

mixedCase.toLowerCase();           // "hello world"
mixedCase.toLocaleLowerCase();     // "hello world" (locale-aware)

mixedCase.toUpperCase();           // "HELLO WORLD"
mixedCase.toLocaleUpperCase();     // "HELLO WORLD"

String Splitting

let csvData = "apple,banana,orange,grape";

// Split by delimiter
csvData.split(",");               // ["apple", "banana", "orange", "grape"]

// Split using regular expression
let mixedString = "one1two2three3";
mixedString.split(/\d+/);          // ["one", "two", "three"]

Regular Expressions

Regular expressions define patterns for matching and extracting string content.

Pattern Creation

// Constructor approach
let patternA = new RegExp("\\d+", "g");
let patternB = new RegExp("\\.", "i");

// Literal syntax (preferred for simple patterns)
let patternC = /\\d+/g;
let patternD = /\\./i;

Common RegExp Methods

let testString = "The year 2024 has 365 days";
let digitPattern = /\\d+/g;

// test() - returns true/false
digitPattern.test(testString);     // true

// exec() - returns array of matches or null
digitPattern.exec(testString);     // ["2024", index: 8, input: ...]

String Methods with RegExp

let sentence = "Cats and dogs are animals";

// match() - extracts all matching content
sentence.match(/\\b[a-z]+/gi);   // ["Cats", "and", "dogs", "are", "animals"]

// replace() - substitutes matched content
sentence.replace(/dogs/g, "cats");  // "Cats and cats are animals"

// search() - returns index of first match
sentence.search(/dogs/);          // 9
sentence.search(/fish/);          // -1 (not found)

// split() - breaks string by pattern
let numbers = "a1b2c3d4";
numbers.split(/[a-z]/);           // ["", "1", "2", "3", "4"]

Pattern Syntax Reference

// Character classes
/[0-9]/           // Any digit
/[a-z]/           // Any lowercase letter
/[A-Z]/           // Any uppercase letter
/[a-zA-Z]/        // Any letter
/\\w/            // Word character [a-zA-Z0-9_]
/\\W/            // Non-word character
/\\d/            // Any digit
/\\D/            // Non-digit
/\\s/            // Whitespace
/\\S/            // Non-whitespace

// Quantifiers
/{3}/             // Exactly 3 times
/{2,5}/           // 2 to 5 times
/{2,}/            // 2 or more times
/+ /               // 1 or more (equivalent to {1,})
/* /               // 0 or more (equivalent to {0,})
/? /               // 0 or 1 (equivalent to {0,1})

// Anchors
/^Start/          // Must start with "Start"
/End$/            // Must end with "End"

// Special characters
/./               // Any single character
/\\./             // Literal dot character
/\\\\/            // Literal backslash

// Boundary markers
/\\bword\\b/      // Word boundary
/\\Bword\\B/      // Non-word boundary

Date and Time

The Date object handles date and time operations in JavaScript.

Creating Date Instances

// Current timestamp
let currentDate = new Date();

// Specific date (Month is 0-indexed)
let customDate = new Date("December 25, 2024 10:30:00");
let alternateDate = new Date(2024, 11, 25, 10, 30, 0);

Date Methods

let now = new Date();

now.getDate();           // Day of month (1-31)
now.getDay();            // Day of week (0=Sunday, 6=Saturday)
now.getMonth();          // Month (0=January, 11=December)
now.getFullYear();       // 4-digit year
now.getHours();          // Hours (0-23)
now.getMinutes();        // Minutes (0-59)
now.getSeconds();        // Seconds (0-59)
now.getMilliseconds();   // Milliseconds (0-999)
now.getTime();           // Unix timestamp (milliseconds since Jan 1, 1970)

// Convenience methods
Date.now();              // Current timestamp

Math Utilities

The Math object provides mathematical constants and functions without requiring object instantiation.

// Constants
Math.PI;                 // 3.1415926535
Math.E;                  // 2.7182818284

// Rounding operations
Math.ceil(4.2);          // 5 (round up)
Math.floor(4.7);         // 4 (round down)
Math.round(4.5);         // 5 (standard rounding)
Math.abs(-10);           // 10 (absolute value)

// Power and roots
Math.pow(2, 3);          // 8 (2 to the power of 3)
Math.sqrt(16);           // 4 (square root)
Math.pow(27, 1/3);       // 3 (cube root)

// Random numbers (0 to 1, exclusive of 1)
Math.random();           // Random value between 0 and 1

// Random integer between min and max (inclusive)
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Min/max of multiple values
Math.max(10, 5, 8, 20);  // 20
Math.min(10, 5, 8, 20);  // 5

JSON Operations

JSON (JavaScript Object Notation) is the standard format for data interchange.

// Converting JavaScript values to JSON string
let userData = {
    name: "Alice",
    age: 30,
    skills: ["JavaScript", "Python"],
    active: true
};

let jsonString = JSON.stringify(userData);
// '{"name":"Alice","age":30,"skills":["JavaScript","Python"],"active":true}'

// Parsing JSON string back to JavaScript object
let parsedData = JSON.parse(jsonString);

// Reviving with custom converter
let dataWithDate = JSON.parse(jsonString, (key, value) => {
    if (key === "createdAt") {
        return new Date(value);
    }
    return value;
});

Document Object Model (DOM)

The DOM represents HTML documents as hierarchical tree structures, enabling programmatic manipulation.

Node Types

// Document node - represents entire HTML document
document;  // Root node, available as window property

// Element nodes - HTML tags (div, p, span, etc.)
let container = document.getElementById("main");

// Text nodes - text content within elements
let paragraph = document.createElement("p");
let text = document.createTextNode("Sample text");

// Attribute nodes - element attributes (not commonly accessed directly)
let link = document.createElement("a");
let hrefAttr = link.getAttributeNode("href");

Query Methods

// By ID (returns single element)
document.getElementById("header");

// By tag name (returns HTMLCollection)
document.getElementsByTagName("div");

// By class name (returns HTMLCollection)
document.getElementsByClassName("container");

// By name attribute (returns NodeList)
document.getElementsByName("username");

CSS Selector Queries

// Returns first matching element
document.querySelector(".article > p");

// Returns all matching elements (NodeList)
document.querySelectorAll("ul li");

// Element-specific queries
let list = document.querySelector("#items");
list.querySelectorAll("li");           // All li descendants
list.querySelector("li:first-child"); // First li child
list.querySelector(".active");         // First .active within list

Child and Sibling Navigation

let parent = document.querySelector(".parent");

// All child nodes (includes text and comment nodes)
parent.childNodes;

// Only element children
parent.children;

// First/last child (any type)
parent.firstChild;
parent.lastChild;

// First/last element child
parent.firstElementChild;
parent.lastElementChild;

// Previous/next sibling (any type)
sibling.previousSibling;
sibling.nextSibling;

// Previous/next element sibling
sibling.previousElementSibling;
sibling.nextElementSibling;

Parenet Navigation

let child = document.querySelector(".child");
child.parentNode;        // Direct parent element

Element Attribute Manipulation

let element = document.getElementById("myElement");

// Get attribute values
element.id;              // "myElement"
element.value;          // Input value
element.className;       // "class1 class2" (not 'class')
element.href;           // For anchor elements

// Set attribute values
element.id = "newId";
element.className = "new-class";
element.value = "updated";

// Boolean attributes
element.disabled = true;
element.checked = false;

// Custom data attributes
element.dataset.customAttr = "value";

Node Content Operations

let container = document.querySelector(".container");

// nodeValue - for text/comment nodes
let textNode = container.firstChild;
textNode.nodeValue;              // Text content

// innerHTML - includes HTML tags
container.innerHTML;             // Gets all inner HTML
container.innerHTML = "<p>New content</p>";  // Sets HTML

// innerText - plain text (CSS-aware)
container.innerText;             // Gets visible text
container.innerText = "Plain text";

// textContent - all text content (ignores CSS)
container.textContent;           // Gets all text

DOM Structure Modifications

// Create new elements
let newDiv = document.createElement("div");
let textNode = document.createTextNode("Content here");

// Append to parent
newDiv.appendChild(textNode);

// Insert before specific child
parentElement.insertBefore(newElement, referenceElement);

// Replace child
parentElement.replaceChild(newElement, oldElement);

// Remove child
parentElement.removeChild(childElement);

// Self-removal pattern
childElement.parentNode.removeChild(childElement);

// Using innerHTML for bulk insertion (caution: replaces existing)
parentElement.innerHTML += "<p>Additional content</p>";

Document Loading Sequence

// Problem: Code runs before elements exist
// Solution 1: Place script at end of body
// <script src="app.js"></script>
// </body>

// Solution 2: Wait for full load
window.addEventListener("load", function() {
    // DOM is fully available here
    document.getElementById("btn").addEventListener("click", handleClick);
});

// DOMContentReady fires when DOM is parsed (faster than load)
document.addEventListener("DOMContentLoaded", function() {
    // DOM is ready, but external resources may still load
});

CSS Style Manipulation

let box = document.querySelector(".box");

// Inline styles via style property
box.style.width = "200px";
box.style.backgroundColor = "#ff0000";
box.style.borderWidth = "2px";

// CSS property names map to camelCase
// background-color -> backgroundColor
// margin-left -> marginLeft
// border-top-width -> borderTopWidth

// Get computed styles (from all sources)
function getComputed(element, property) {
    if (window.getComputedStyle) {
        return getComputedStyle(element, null)[property];
    } else {
        return element.currentStyle[property];
    }
}

Layout Properties

let box = document.querySelector(".box");

// Visible dimensions (content + padding)
box.clientHeight;    // Height including padding
box.clientWidth;     // Width including padding

// Full dimensions (content + padding + border)
box.offsetHeight;    // Total height
box.offsetWidth;     // Total width

// Offset from positioned ancestor
box.offsetParent;    // Nearest positioned ancestor
box.offsetLeft;      // Horizontal offset
box.offsetTop;       // Vertical offset

// Scroll properties
box.scrollHeight;    // Full scrollable height
box.scrollWidth;     // Full scrollable width
box.scrollTop;       // Vertical scroll position
box.scrollLeft;      // Horizontal scroll position

// Check if scrolled to edge
let atBottom = (box.scrollHeight - box.scrollTop) === box.clientHeight;
let atRight = (box.scrollWidth - box.scrollLeft) === box.clientWidth;

Event Handling

Events enable responsive interactions between users and the page.

Event Binding Approaches

let button = document.getElementById("submitBtn");

// Method 1: Inline HTML attribute (not recommended)
// <button onclick="handleClick()">Submit</button>

// Method 2: DOM property assignment (simple cases)
button.onclick = function(event) {
    console.log("Button clicked!");
};

// Method 3: addEventListener (recommended - supports multiple handlers)
button.addEventListener("click", handleClick);
button.addEventListener("click", anotherHandler);

function handleClick(event) {
    console.log("Clicked at:", event.type);
}

Event Object Properties

element.addEventListener("click", function(e) {
    // Mouse position relative to viewport
    e.clientX;      // Horizontal coordinate
    e.clientY;      // Vertical coordinate
    
    // Mouse position relative to document
    e.pageX;
    e.pageY;
    
    // Mouse position relative to target element
    e.offsetX;
    e.offsetY;
    
    // Screen position
    e.screenX;
    e.screenY;
    
    // Mouse button (0=left, 1=middle, 2=right)
    e.button;
    
    // Modifier keys
    e.shiftKey;     // Shift pressed?
    e.ctrlKey;      // Ctrl pressed?
    e.altKey;       // Alt pressed?
    e.metaKey;      // Meta/Command pressed?
});

Keyboard Events

document.addEventListener("keydown", function(e) {
    e.key;          // Key value (e.g., "a", "Enter")
    e.code;         // Physical key code (e.g., "KeyA")
    e.keyCode;      // Legacy numeric code (deprecated)
    e.repeat;       // Key being held down?
});

document.addEventListener("keyup", function(e) {
    console.log("Released:", e.key);
});

document.addEventListener("keypress", function(e) {
    console.log("Character:", e.key);
});

Preventing Default Behaviors

// Prevent form submission
form.addEventListener("submit", function(e) {
    e.preventDefault();
});

// Prevent link navigation
link.addEventListener("click", function(e) {
    e.preventDefault();
});

// Stop event propagation
button.addEventListener("click", function(e) {
    e.stopPropagation();  // Prevents bubbling/capturing
    
    // Also prevents other handlers on same element
    // e.stopImmediatePropagation();
});

Event Propagation Phases

// Capturing phase: window -> target (first)
element.addEventListener("click", handler, true);  // true = capture

// Target phase: event reaches element

// Bubbling phase: target -> window (default)
element.addEventListener("click", handler, false); // false = bubble

Event Delegation

// Instead of binding to each item, delegate to container
let list = document.getElementById("itemList");

list.addEventListener("click", function(e) {
    if (e.target.matches("li")) {
        console.log("Item clicked:", e.target.textContent);
    }
});

// Add new items - automatically work with delegation
let newItem = document.createElement("li");
newItem.textContent = "Dynamic item";
list.appendChild(newItem);

Browser Object Model (BOM)

The BOM provides browser-specific objects and methods.

Window Object

// Window dimensions
window.innerWidth;   // Viewport width
window.innerHeight;  // Viewport height
window.outerWidth;   // Browser window width
window.outerHeight;  // Browser window height

// Timer functions
let timeoutId = setTimeout(function() {
    // Executes once after delay
}, 1000);
clearTimeout(timeoutId);

let intervalId = setInterval(function() {
    // Repeats every interval
}, 1000);
clearInterval(intervalId);

// Animation-friendly timing
function animate(callback) {
    let start = null;
    function step(timestamp) {
        if (!start) start = timestamp;
        let progress = timestamp - start;
        callback(progress);
        if (progress < 2000) {
            requestAnimationFrame(step);
        }
    }
    requestAnimationFrame(step);
}

Dialog Boxes

// Simple alert
alert("Notice message");

// Confirmation dialog (returns boolean)
let confirmed = confirm("Are you sure?");

// Prompt dialog (returns input or null)
let name = prompt("Enter your name:", "Guest");

Location Object

// Current URL
console.log(window.location.href);

// Navigate to new URL
window.location.href = "https://example.com";
window.location.assign("https://example.com");

// Replace (no history entry)
window.location.replace("https://example.com");

// Reload page
window.location.reload();        // Cached reload
window.location.reload(true);    // Force fresh download

// Parse URL components
console.log(location.protocol);  // "https:"
console.log(location.hostname);  // "example.com"
console.log(location.port);      // "443"
console.log(location.pathname);  // "/path/"
console.log(location.search);    // "?param=value"

Navigator Object

// Browser information
console.log(navigator.userAgent);

// Detect browser type
let ua = navigator.userAgent;
if (ua.includes("Firefox")) {
    console.log("Firefox browser");
} else if (ua.includes("Chrome") && !ua.includes("Edg")) {
    console.log("Chrome browser");
} else if (ua.includes("MSIE") || ua.includes("Trident")) {
    console.log("Internet Explorer");
} else if ("ActiveXObject" in window) {
    console.log("IE 11+");
}

History Object

// Navigation
history.back();      // Go to previous page
history.forward();   // Go to next page
history.go(-1);      // Go back 1 page
history.go(1);       // Go forward 1 page

// History entry count
console.log(history.length);

Screen Object

// Display information
console.log(screen.width);        // Screen width
console.log(screen.height);       // Screen height
console.log(screen.availWidth);   // Available width (excluding taskbar)
console.log(screen.availHeight);  // Available height

Practical Examples

Smooth Animation Function

function animateElement(element, property, target, duration, callback) {
    element.style.transition = `${property} ${duration}ms ease`;
    element.style[property] = target + "px";
    
    setTimeout(() => {
        element.style.transition = "";
        callback && callback();
    }, duration);
}

// Usage
let box = document.querySelector(".box");
animateElement(box, "left", 300, 500, () => console.log("Done!"));

Carousel Implementation

class Carousel {
    constructor(container) {
        this.container = container;
        this.items = container.querySelectorAll(".slide");
        this.current = 0;
        this.autoPlay();
    }
    
    show(index) {
        this.items.forEach((item, i) => {
            item.style.display = i === index ? "block" : "none";
        });
        this.current = index;
    }
    
    next() {
        let nextIndex = (this.current + 1) % this.items.length;
        this.show(nextIndex);
    }
    
    autoPlay() {
        setInterval(() => this.next(), 3000);
    }
}

Dropdown Menu

class DropdownMenu {
    constructor(trigger) {
        this.trigger = trigger;
        this.menu = trigger.nextElementSibling;
        this.bindEvents();
    }
    
    bindEvents() {
        this.trigger.addEventListener("click", () => this.toggle());
        
        document.addEventListener("click", (e) => {
            if (!this.trigger.contains(e.target) && 
                !this.menu.contains(e.target)) {
                this.close();
            }
        });
    }
    
    toggle() {
        this.menu.classList.toggle("visible");
    }
    
    close() {
        this.menu.classList.remove("visible");
    }
}

Tags: javascript DOM BOM events regular expressions

Posted on Fri, 12 Jun 2026 16:13:34 +0000 by AbraCadaver