Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Manipulating Web Pages with JavaScript DOM and BOM

Tech 1

DOM Manipulation

DOM operations include creating, adding, deleting, modifying, querying, attribute handling, and event management.

Creating Elements

Use document.createElement(), innerHTML, or innerText.

Adding Elements

Employ appendChild() or insertBefore().

Deleting Elements

Utilize removeChild().

Modifying Elements

  • Attributes: Update src, href, title, etc.
  • Content: Change via innerHTML or innerText.
  • Form Elements: Adjust value, type, disabled.
  • Styles: Modify using style property or className.

Querying Elements

  • Legacy Methods: getElementById, getElementsByTagName (less preferred).
  • Modern Methods: querySelector and querySelectorAll (recommended).
  • Node Traversal: Access parent (parentNode), children (children), and siblings (previousElementSibling, nextElementSibling).

Attribute Operations

For custom attributes, use setAttribute(), getAttribute(), and removeAttribute().

Event Handling

Common mouse events include click, mouseover, mouseout, focus, blur, mousemove, mouseup, and mousedown.

DOM Element Operations

Accessing DOM Elements

  • Using querySelector and querySelectorAll:
    const singleElement = document.querySelector('.example');
    const multipleElements = document.querySelectorAll('.list-item');
    
  • Special Elements:
    const bodyElement = document.body;
    const htmlElement = document.documentElement;
    

Modifying Content and Attributes

Event handling involves three components: the event source, event type, and event handler.

  • Content Modification:
    • document.write() (limited use).
    • innerText and innerHTML.
  • Attribute Modification:
    • Common attributes: src, type, title.
    • CSS styles via style property (use camelCase for hyphenated properties).
    • CSS classes via className or classList for adding/removing classes.
  • Form Elements: Update properties like value and disabled.

Timers

Use setInterval() for recurring functions and setTimeout() for delayed execution.

Event Fundamentals

Registering Events

  • DOM Level 0: element.onclick = function() {} (bubbling only).
  • DOM Level 2: element.addEventListener('click', handler, useCapture) (supports capturing and bubbling).

Event Components

  1. Event source: The target DOM element.
  2. Event type: e.g., click, mouseover.
  3. Event handler: Function executed on event trigger.

Advanced Functions

Functions can be treated as values, enabling expressions and callbacks.

Context with this

this refers to the element that triggered the event.

const actionButton = document.querySelector('.action-btn');
actionButton.onclick = function() {
    this.style.color = 'blue';
};

Exclusive State Pattern

Deactivate other elements too highlight a selected state.

Custom Attributes

Prefix custom attributes with data- for HTML5 compliance.

Node Operations

Finding Nodes

  • Parenet: childNode.parentNode.
  • Children: parentElement.children (returns element nodes).
  • Siblings: previousElementSibling and nextElementSibling.

Adding Nodes

  1. Create a node with document.createElement().
  2. Insert it using appendChild() or insertBefore().

Cloning Nodes

cloneNode(true) clones an element and its descendants; cloneNode(false) clones only the element.

Deleting Nodes

Use removeChild() to delete a node entire, unlike hiding with CSS (display: none).

Advanced Event Handling

Event Object

The event object provides details about the event, accessible in handlers.

Common Event Properties

  • Keyboard Events: Use event.key instead of deprecated keyCode.
  • Other Events: Properties like target, type.

Event Flow

Events propagate through capture, target, and bubbling phases. Use event.stopPropagation() to halt flow and event.preventDefault() to block default actions.

Event Delegation

Attach event listeners to parent elements to manage events for multiple child elements efficiently.

Removing Events

Use removeEventListener() to detach event handlers.

BOM Overview

BOM (Browser Object Model) interacts with the browser window, distinct from DOM.

Window Object Events

  • Load Events: window.onload and document.addEventListener('DOMContentLoaded', handler).
  • Resize Events: window.onresize for window size changes.

Timers

  • setTimeout() executes a function once after a delay.
  • setInterval() repeats execution at intervals.
const timeoutId = setTimeout(() => console.log('Delayed'), 1000);
clearTimeout(timeoutId);

const intervalId = setInterval(() => console.log('Repeating'), 2000);
clearInterval(intervalId);

JavaScript Execution Mechanism

JavaScript operates on a single-threaded event loop, handling asynchronous tasks via callbacks.

Location Object

  • Properties: href, search.
  • Methods: assign(), reload().

Navigator Object

Access browser details via navigator.userAgent.

History Object

Manage browser history with history.back(), history.forward().

PC Web Effects

Mouse Events

mouseenter and mouseover differ in event bubbling behavior.

Element Dimensions and Position

  • Offset Series: offsetLeft, offsetTop for position.
  • Client Series: clientWidth, clientHeight for size.
  • Scroll Series: scrollTop, scrollLeft for scroll distance.

Animation Functions

Encapsulate animation logic for smooth transitions using timing functions.

Throttling

Implement throttling to limit function execution rate during events like scrolling.

Mobile Web Effects

Touch Events

Handle touchstart, touchmove, and touchend events with TouchEvent objects.

Click Delay Solutions

  • Disable zooming.
  • Use libraries like FastClick.

Mobile Plugins

  • Swiper: For touch sliders.
  • Other plugins enhance mobile interactions.

Regular Expressions

Syntax

Define patterns and match strings using test() and exec() methods.

const pattern = /\d+/;
console.log(pattern.test('123')); // true

Metacharacters

Use symbols like ., *, +, ? to define patterns.

Modifiers

Apply flags like g (global) and i (case-insensitive) to regex.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.