如何基于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
thisat 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
相关产品推荐
相关产品推荐

