You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于JavaScript DOM方法实现jQuery风格的append函数

Implementing jQuery-style append for Custom $ Function

Got it, let's tackle implementing the append method for your custom $ function to match jQuery's behavior. Here's a solution that follows the core specifications of jQuery's append method, handling different input types and supporting chaining.

The Implementation Code

function $(selector){
  if ( !(this instanceof $)){
    return new $(selector);
  }
  this.selectors = document.querySelectorAll(selector);
};

$.prototype.append = function(code) {
  // Helper function to convert input into a valid array of DOM nodes
  const convertToNodes = (input) => {
    let nodes = [];
    
    // Case 1: Input is an HTML string
    if (typeof input === 'string') {
      const tempContainer = document.createElement('div');
      tempContainer.innerHTML = input;
      nodes = Array.from(tempContainer.childNodes);
    }
    // Case 2: Input is a single DOM element
    else if (input instanceof Node) {
      nodes = [input];
    }
    // Case 3: Input is another instance of our custom $ object
    else if (input instanceof $) {
      nodes = Array.from(input.selectors);
    }
    // Case 4: Input is a NodeList or array of DOM elements
    else if (input instanceof NodeList || Array.isArray(input)) {
      nodes = Array.from(input).filter(item => item instanceof Node);
    }
    
    return nodes;
  };

  const nodesToAppend = convertToNodes(code);
  if (nodesToAppend.length === 0) return this; // Exit early if no valid nodes

  // Iterate over each target element in our selected set
  Array.from(this.selectors).forEach((targetEl, targetIndex) => {
    nodesToAppend.forEach(node => {
      if (targetIndex === 0) {
        // First target gets the original node (DOM elements can only exist once in the DOM)
        targetEl.appendChild(node);
      } else {
        // Subsequent targets get a deep clone of the node
        targetEl.appendChild(node.cloneNode(true));
      }
    });
  });

  // Return the $ instance to support method chaining
  return this;
};

Key Details Explained

Let's break down how this matches jQuery's behavior:

  • HTML String Input: When you pass an HTML string (like <span>Hi</span>), we create a temporary container to parse the string into DOM nodes, then append those nodes to each target element.
  • Single DOM Element: If you pass a single DOM element, it will be moved to the first target element. For subsequent targets, we create a deep clone (so each target gets its own copy, following jQuery's behavior for multiple targets).
  • Custom $ Object/NodeList: When passing another $ instance or a NodeList, we convert it to an array of DOM nodes, then clone each node for every target element (keeping the original nodes in their original positions).
  • Chaining Support: Just like jQuery, we return this at the end so you can chain other methods (e.g., $('.box').append('<p>Test</p>').addClass('updated')).

Example Usage

// Append HTML string to all .container elements
$('.container').append('<div class="new-item">New Content</div>');

// Move a single DOM element to the last .target element (and clone for others if multiple)
const myButton = document.getElementById('submit-btn');
$('.target').append(myButton);

// Append all <p> elements (cloned) to each .wrapper
const $paragraphs = $('p');
$('.wrapper').append($paragraphs);

内容的提问来源于stack exchange,提问作者S.Jobs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:42:02