banner
Jrenc

Jrenc

There’s a million things I haven’t done。
x
github
email
bilibili

How JS Works on Html

What is the difference between document and window?#

In short, both document and window are objects, and they play different roles in the Web API.

Window Object#

  • Window Object
    The window represents a browser window or tab and is the global object in JavaScript. It provides many methods and properties to control the browser window.
    Scope: The window is the top-level object, and any JavaScript code in the browser can directly access the window and its properties and methods without any prefix.
    Functionality: The window object contains properties of the browser window, such as size, position, etc., and also provides methods to control the behavior of the browser window, such as opening new windows, timer functions (setTimeout, setInterval), browser history control, etc. Additionally, it is the host for all global variables and functions.

Document Object#

  • Document Object
    Definition: The document object is a property of the window object, representing the HTML document loaded in the window and serving as the entry point to the Document Object Model (DOM).
    Scope: The document object is specifically used to manipulate and access the content of the document, such as HTML elements, CSS styles, etc.
    Functionality: The document object provides many methods to access and modify the content of the document, such as getting and setting the content of elements, creating new HTML elements, querying selectors, etc. Through the document object, dynamic modifications and interactions with the page content can be achieved.

In summary, the window object represents the browser window itself and is the parent object of all global JavaScript objects, functions, and variables, while the document object represents the document loaded in the window and is the container for all HTML document elements. In practical development, whether to use window or document depends on whether you need to manipulate the browser window itself or the content of the document within the window.
Simply put, the DOM object manipulates the content of the document, while the window object manipulates the properties and methods of the browser window. So, if you want to set a timer or monitor changes in the window, you need to use the window object; if you want to change the content of the document, you need to use the document object.
So at that time, the main problem with the Gantt chart was that I didn't know the difference between the window API and the document API. I didn't understand native HTML, and when this knowledge was missing, I naturally wouldn't design this logic.
So essentially, it’s about using the encapsulated API.

Learning DOM Stream API#

How to Get Elements#

Getting elements in the DOM mainly involves the following APIs:

  1. getElementById()

    • Gets a single element by its ID. The ID should be unique within an HTML document.
    let element = document.getElementById('elementId'); // Get element by ID
    
  2. getElementsByClassName()

    • Gets a collection of elements by their class name. This method returns a live HTMLCollection of all elements with the specified class name.
    let elements = document.getElementsByClassName('className'); // Get collection of elements by class name
    
  3. getElementsByTagName()

    • Gets a collection of elements by their tag name (e.g., div, p, a, etc.). It also returns a live HTMLCollection of all elements with the specified tag name.
    let elements = document.getElementsByTagName('tagName'); // Get collection of elements by tag name
    
  4. querySelector()

    • Gets the first matching element using a CSS selector. This is a very powerful method that allows you to use complex CSS selectors to locate elements.
    let element = document.querySelector('.className'); // Get the first matching element using a CSS selector
    
  5. querySelectorAll()

    • Gets a collection of all matching elements using a CSS selector. This method returns a NodeList of all elements that match the specified CSS selector.
    let elements = document.querySelectorAll('.className'); // Get all matching elements using a CSS selector
    
  6. closest()

    • Starts from the element itself and finds the first ancestor element (including itself) that matches the given CSS selector. This method is useful for finding the closest parent match. It searches upwards.
    let closestElement = element.closest('.className'); // Find the closest matching ancestor element
    
  7. children

    • Gets a collection of a given element's child elements, excluding text and comment nodes. This is a property of the element object that returns an HTMLCollection of direct child elements.
    let childElements = parentElement.children; // Get all direct child elements of parentElement
    
  8. childNodes

    • Gets all child nodes of an element, including element nodes, text nodes, and comment nodes. This is also a property of the element object that returns a NodeList.
    let childNodes = parentElement.childNodes; // Get all child nodes of parentElement, including text and comments
    
  9. parentElement and parentNode

    • Gets the parent element of a given element. parentElement returns the parent element node, while parentNode can return any type of parent node, including text nodes and comment nodes.
    let parent = childElement.parentElement; // Get the parent element of childElement
    let parentNode = childElement.parentNode; // Get the parent node of childElement
    
  10. nextSibling and previousSibling

    • Gets the next and previous sibling nodes of an element, respectively. These properties can return any type of node, including element nodes, text nodes, and comment nodes.
    let nextNode = element.nextSibling; // Get the next sibling node of element
    let prevNode = element.previousSibling; // Get the previous sibling node of element
    
  11. nextElementSibling and previousElementSibling

    • Similar to nextSibling and previousSibling, but these properties only return element nodes, ignoring text nodes and comment nodes.
    let nextElement = element.nextElementSibling; // Get the next sibling element of element
    let prevElement = element.previousElementSibling; // Get the previous sibling element of element
    
  12. firstChild and lastChild

    • Gets the first and last child nodes of an element, respectively. These child nodes can be any type of node, including element nodes, text nodes, and comment nodes.
    let first = parentElement.firstChild; // Get the first child node of parentElement
    let last = parentElement.lastChild; // Get the last child node of parentElement
    
  13. firstElementChild and lastElementChild

    • Similar to firstChild and lastChild, but these properties only return element nodes, ignoring text nodes and comment nodes.
    let firstElement = parentElement.firstElementChild; // Get the first child element of parentElement
    let lastElement = parentElement.lastElementChild; // Get the last child element of parentElement
    

By comprehensively using these APIs, you can effectively traverse and manipulate the DOM tree, achieving flexible control over the page structure.

Through these APIs, you can flexibly retrieve single or multiple elements from the DOM tree based on different conditions and needs.


How to Create Elements#

Create Elements#

document.createElement('tag')

Create Text Nodes#

document.createTextNode('text')

What is a text node?
A text node is the text within HTML, such as the text in a p tag, the text in an a tag, etc.
How to use createTextNode?

var text = document.createTextNode('text')

What is the effect?

<p>text</p>

Here, text is the content of the text.


How to Add Elements#

Add Elements#

parent.appendChild(child)

What is the effect?

<div>
  <p>text</p>
</div>

Insert Elements#

parent.insertBefore(newNode, referenceNode)

For example:

var parent = document.getElementById('parent')
var newNode = document.createElement('p')
var referenceNode = document.getElementById('reference')
parent.insertBefore(newNode, referenceNode)

What is the effect?

<div id="parent">
  <p>newNode</p>
  <p id="reference">referenceNode</p>
</div>

What role does referenceNode play?
referenceNode is a reference node, and its role is to insert the new node before the reference node.

How to Delete Elements#

Delete Elements#

parent.removeChild(child)

For example:

var parent = document.getElementById('parent')
var child = document.getElementById('child')
parent.removeChild(child)

What is the effect? Provide a comparison.

<div id="parent">
  <p id="child">child</p>
</div>
<div id="parent">
</div>

How to Modify Element Content?#

Modifying element content in the DOM (Document Object Model) mainly involves the following commonly used APIs:

  1. innerText and textContent
    Both properties can be used to get or set the text content of an element. innerText reflects the "rendered" text content of the element and its child elements, i.e., the content displayed on the page according to styles, while textContent gets or sets the content of all child nodes of the element, including text within <script> and <style> tags.

    element.innerText = 'New text content'; // Set the visible text of the element
    let content = element.innerText; // Get the visible text of the element
    
    element.textContent = 'New full text content'; // Set the full text of the element, including all child nodes
    let fullContent = element.textContent; // Get the full text of the element, including all child nodes
    
  2. innerHTML
    The innerHTML property can be used to get or set the HTML content within an element. Unlike innerText and textContent, innerHTML will include all HTML tags.

    element.innerHTML = '<strong>Bold text</strong>'; // Set the HTML content within the element
    let htmlContent = element.innerHTML; // Get the HTML content within the element
    
  3. outerHTML
    The outerHTML property can get or set the HTML that includes the element itself and all its child nodes.

    element.outerHTML = '<div><strong>New element and its content</strong></div>'; // Replace the element and its content
    
  4. createElement and appendChild / replaceChild
    These methods are used to create new DOM elements and insert them into the document. createElement is used to create a new element node, appendChild is used to add the created node to the end of the parent node's child node list, and replaceChild is used to replace a child node of the parent node.

    let newElement = document.createElement('div'); // Create a new div element
    newElement.innerText = 'This is a newly created element'; // Set the text content of the new element
    parentElement.appendChild(newElement); // Add the new element as a child of parentElement
    
    let anotherElement = document.createElement('span'); // Create another element
    parentElement.replaceChild(anotherElement, newElement); // Replace the child element in the parent element
    

Through these APIs, you can easily modify the content and structure of elements in the DOM.
Modifying the styles and attributes of elements in the DOM mainly involves the following APIs:

  1. Modify Styles: style Property

    • Each DOM element has a style property that allows you to directly modify the element's styles through JavaScript. You can change styles by setting CSS properties in the element's style property.
    element.style.backgroundColor = 'red'; // Directly set the background color of the element to red
    element.style.fontSize = '20px'; // Set the font size of the element to 20 pixels
    
  2. Modify Classes: classList Property

    • classList provides a simple way to manipulate the collection of class names of an element. Common methods include add(), remove(), toggle(), and contains().
    element.classList.add('new-class'); // Add a new class name
    element.classList.remove('old-class'); // Remove a class name
    element.classList.toggle('active'); // If it exists, remove the class name; if not, add it
    
  3. Set and Get Attributes: setAttribute() and getAttribute()

    • These two methods are used to set and get the attributes of an element. Attributes can be standard HTML attributes, such as id, src, href, etc., or custom attributes.
    element.setAttribute('data-custom', 'value'); // Set a custom attribute
    let value = element.getAttribute('data-custom'); // Get the value of this custom attribute
    
  4. Directly Modify Attributes

    • For some common HTML attributes, such as id, src, href, etc., you can directly get and set them through the element object.
    element.href = 'https://example.com'; // Directly set the href attribute of the element
    let elementId = element.id; // Directly get the id attribute of the element
    

Through these APIs, you can conveniently modify the styles and attributes of DOM elements in JavaScript to achieve dynamic page effects.

How to Replace Elements#

Replace Elements#

In DOM manipulation, replacing elements involves the following commonly used APIs:

  1. replaceChild(newChild, oldChild)

    • This is a method called on the parent node to replace an old child node with a new child node. newChild is the new node to be inserted, while oldChild is the old node to be replaced.
    parentNode.replaceChild(newElement, oldElement); // Replace oldElement in parentNode with newElement
    
  2. replaceWith(...)

    • The replaceWith() method allows you to replace a DOM node (or multiple nodes) with a specified node or a segment of HTML or text string. This method is called directly on the node to be replaced.
    oldElement.replaceWith(newElement); // Replace oldElement with newElement
    
  3. Using insertBefore() with removeChild() or remove() to achieve replacement

    • Although not a direct replacement method, you can achieve the effect of replacement by first inserting the new node before the old node and then removing the old node.
    parentNode.insertBefore(newElement, oldElement); // Insert newElement before oldElement
    parentNode.removeChild(oldElement); // Remove oldElement to achieve the replacement effect
    // Or use the more concise oldElement.remove() if the environment supports it
    oldElement.remove();
    
  4. Using outerHTML

    • By setting the outerHTML property of an element, you can directly replace the entire element, including the element itself and its content. This method does not require first obtaining the parent node.
    oldElement.outerHTML = '<div id="newElement">New content</div>'; // Replace oldElement with new HTML content, including the element itself
    

These APIs provide flexible ways to replace elements in the DOM, allowing you to choose the appropriate method based on different scenarios and needs.

How to Add Events to Elements#

Handling element events in the DOM mainly involves the following APIs:

  1. addEventListener(event, handler, [options])

    • Used to add an event listener to a specified element. event is the type of event to listen for (e.g., "click", "mouseover", etc.), handler is the function to call when the event occurs, and options is an optional parameter for specifying more detailed event listening behavior.
    element.addEventListener('click', function() {
      console.log('Element was clicked');
    });
    
  2. removeEventListener(event, handler, [options])

    • Used to remove an event listener that was previously added with addEventListener. Note that handler must be the same function reference used when adding the listener.
    function handleClick() {
      console.log('Element was clicked');
    }
    
    element.addEventListener('click', handleClick);
    // Later remove the listener
    element.removeEventListener('click', handleClick);
    
  3. dispatchEvent(event)

    • Used to trigger a specified event on a given element. event is an instance of an Event object, which can be created using new Event().
    let event = new Event('customEvent');
    element.dispatchEvent(event); // Trigger a custom event
    
  4. Assigning event handlers directly through properties

    • You can directly assign event handler functions to the event handling properties of elements. For example, onclick corresponds to the click event.
    element.onclick = function() {
      console.log('Element was clicked');
    };
    
  5. Using properties with the on prefix to set event handler functions

    • In addition to onclick, there are many other events that can be added by setting properties that start with on, such as onmouseover, onkeydown, etc.
    element.onmouseover = function() {
      console.log('Mouse is over the element');
    };
    
  6. Using the Event object

    • The event parameter in the event handler function is an instance of the Event object, which provides information about the event, such as the element that triggered the event, the event type, and other properties and methods related to the specific event.
    element.addEventListener('click', function(event) {
      console.log('Click occurred on ' + event.target.tagName + ' element');
    });
    
  7. preventDefault()

    • The preventDefault() method of the event object is used to prevent the default behavior of the event. This is useful in scenarios such as preventing a link from navigating away or preventing a form from submitting and reloading the page.
    element.addEventListener('click', function(event) {
      event.preventDefault(); // Prevent the default link navigation behavior
    });
    
  8. stopPropagation()

    • Used to prevent the event from bubbling up to parent elements. Event bubbling refers to the process where the event starts from the deepest node and then propagates up to shallower nodes.
    element.addEventListener('click', function(event) {
      event.stopPropagation(); // Prevent the event from continuing to bubble
    });
    
  9. Event Delegation

    • By utilizing the property of event bubbling, you can set the event listener on a parent element instead of each child element. When the event is triggered on a child element and bubbles up to the parent, you can check the target property of the event to determine which child element triggered the event.
    parentElement.addEventListener('click', function(event) {
      if (event.target && event.target.matches('button.child')) {
        console.log('Child button was clicked');
      }
    });
    
  10. capture Event Capturing

    • In the third parameter of the addEventListener, you can set capture to true to specify that the event handler should execute in the capturing phase rather than the bubbling phase. Event capturing refers to the process where the event starts from the outermost layer and then propagates down to the deepest node.
    element.addEventListener('click', function() {
      console.log('Event handler in capturing phase');
    }, {capture: true});
    
  11. once Option

    • In the third parameter of addEventListener, setting once: true allows the event handler to execute only once and then be automatically removed.
    element.addEventListener('click', function() {
      console.log('This event handler will only execute once');
    }, {once: true});
    

Through these APIs, you can flexibly add, remove, and trigger events for DOM elements, achieving rich interactive effects.

Lifecycle#

The DOM (Document Object Model) and the Window object play important roles in the lifecycle of a web page. Below are some APIs related to the lifecycle of the DOM and Window:

  1. Window Lifecycle Events:

    • load Event

      • When the entire page and all dependent resources such as stylesheets and images have finished loading, the window object triggers the load event.
      window.addEventListener('load', function() {
          console.log('The page has fully loaded');
      });
      
    • DOMContentLoaded Event

      • When the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading, the document object triggers the DOMContentLoaded event.
      document.addEventListener('DOMContentLoaded', function() {
          console.log('DOM content has loaded');
      });
      
    • unload Event

      • When the user leaves the current page, the window object triggers the unload event. This event can be used for cleanup tasks, such as closing pop-up windows.
      window.addEventListener('unload', function() {
          console.log('User has left the page');
      });
      
    • beforeunload Event

      • Triggered before the window, document, or its resources are about to be unloaded. It can be used to ask the user if they are sure they want to leave the current page, typically used to prompt users to save unsaved changes.
      window.addEventListener('beforeunload', function(event) {
          event.returnValue = 'You have unsaved changes, are you sure you want to leave?';
      });
      
  2. Request Animation Frame:

    • requestAnimationFrame(callback)

      • Provides a way to call specific code before the browser repaints, useful for executing animations or page redraws. This method is more efficient than traditional setInterval and can execute animations more smoothly.
      function animate() {
          // Animation code
          requestAnimationFrame(animate);
      }
      requestAnimationFrame(animate);
      
  3. Page Visibility API:

    • This API provides the visibilitychange event and the document.hidden property to detect whether the page is visible to the user. This is particularly useful for optimizing page performance and user experience, such as pausing video playback or stopping animations when the page is not visible.
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            console.log('Page is not visible');
        } else {
            console.log('Page is visible');
        }
    });
    
  4. Performance API:

    • The performance object allows access to performance data related to the current page. For example, you can use performance.timing to analyze the time taken for different stages, such as page loading and parsing.
    window.addEventListener('load', function() {
        setTimeout(function() {
            const timing = performance.timing;
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            console.log('Page load time: ' + loadTime);
        }, 0);
    });
    
  5. resize Event:

    • When the browser window is resized, the window object triggers the resize event. This can be used to adjust page layout or perform other operations in response to window size changes.
    window.addEventListener('resize', function() {
        console.log('Window size has changed');
    });
    
  6. scroll Event:

    • When the user scrolls the page, the scroll event is triggered. This can be used to implement lazy loading (delayed loading of images and other content) or dynamically change the style of the navigation bar.
    window.addEventListener('scroll', function() {
        console.log('The page has been scrolled');
    });
    
  7. focus and blur Events:

    • When the page or an element within the page gains or loses focus, the focus and blur events are triggered. This can be used to improve user experience in form inputs or manage keyboard shortcuts in an application.
    window.addEventListener('focus', function() {
        console.log('Window has gained focus');
    });
    
    window.addEventListener('blur', function() {
        console.log('Window has lost focus');
    });
    

By combining these APIs, developers can more finely control and optimize the behavior and performance of web applications, enhancing user interaction experiences.

By listening to and handling these lifecycle events, you can better control the loading, rendering, and unloading processes of web pages, improving user experience.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.