Create an API that works the same way as jQuery without using the jQuery library:

First, confirm the following two requirements:

 var $div = $('div'1)$div.addClass('red'// Add a red 2 to the class of all divs$div.setText('hi'JQuery is essentially a constructor function. We need to give it an argument to return a jQuery instance of that argument. window.jQuery=function() {}Copy the code

The core idea of jQuery is to select before processing, jQuery constructor parameters, mainly CSS selector. Select a parameter, for example, requirement 1 is to let

Class =’red’, where ‘div’ is the argument to be passed in.

2.

window.jQuery=function (nodeOrSelector){
  var nodes={}
  let temp=document.querySelectorAll(nodeOrSelector)
  for(leti=0; i<temp.length; i++){ nodes[i]=temp[i] } nodes.length=temp.lengthreturn nodes
}
Copy the code

Using document. QuerySelectorAll because it follows the rules of the CSS selector, can help us to get one or more element nodes, use it to determine the result of the selected parameters, can access to multiple results in an HTML document, the result set is a pseudo array, traverse the pseudo array, Store the results of the traversal in the Nodes object.

3.

window.jQuery=function (nodeOrSelector){
  var nodes={}
  let temp=document.querySelectorAll(nodeOrSelector)
  for(leti=0; i<temp.length; i++){ nodes[i]=temp[i] } nodes.length=temp.length nodes.addClass=function (className) {
    for(i=0; i<nodes.length; i++){ nodes[i].classList.add(className) } }return nodes
}
Copy the code

After obtaining the Nodes object, create a constructor for Nodes. The className in this constructor is the parameter to be entered when the window.jQuery property addClass is used. Inside this function, a for loop is created that iterates over Nodes, adding a className to the corresponding node in nodes each round.

You can implement requirement 1.

(4)

window.jQuery=function (nodeOrSelector){
   var nodes={}
   let temp=document.querySelectorAll(nodeOrSelector)
   for(leti=0; i<temp.length; i++){ nodes[i]=temp[i] } nodes.length=temp.length nodes.addClass=function (className) {
    for(i=0; i<nodes.length; i++){ nodes[i].classList.add(className) } } nodes.setText=function (text){
  for(i=0; i<nodes.length; i++){ nodes[i].textContent=text } }return nodes
}
Copy the code

$= jQuery As in requirement 1, Nodes. setText takes a text argument and creates a for loop inside the function that iterates over Nodes and adds a text to each of the nodes.

Then the two apis can fulfill these two requirements. They can add class and textContent to one or more element nodes at the same time.