Manipulating Web Pages with JavaScript DOM and BOM
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
innerHTMLorinnerText. - Form Elements: Adjust
value,type,disabled. - Styles: Modify using
styleproperty orclassName.
Querying Elements
- Legacy Methods:
getElementById,getElementsByTagName(less preferred). - Modern Methods:
querySelectorandquerySelectorAll(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
querySelectorandquerySelectorAll: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).innerTextandinnerHTML.
- Attribute Modification:
- Common attributes:
src,type,title. - CSS styles via
styleproperty (use camelCase for hyphenated properties). - CSS classes via
classNameorclassListfor adding/removing classes.
- Common attributes:
- Form Elements: Update properties like
valueanddisabled.
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
- Event source: The target DOM element.
- Event type: e.g.,
click,mouseover. - 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:
previousElementSiblingandnextElementSibling.
Adding Nodes
- Create a node with
document.createElement(). - Insert it using
appendChild()orinsertBefore().
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.keyinstead of deprecatedkeyCode. - 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.onloadanddocument.addEventListener('DOMContentLoaded', handler). - Resize Events:
window.onresizefor 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,offsetTopfor position. - Client Series:
clientWidth,clientHeightfor size. - Scroll Series:
scrollTop,scrollLeftfor 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.