Handwritten a simple JQuery

Keywords: Front-end JQuery Attribute

Test samples
<!--Test samples-->
<body>
  <div id="jq">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
</body>
Why does jq use $(selector) to get DOM
How to implement native js
//It turns out that it's possible to pass in either an id selector or a class selector 
document.querySelectorAll(selector)
Get the first few elements in DOM
// Because what we get is a NodeList array, of course, we can get it by subscript (don't cross the boundary)
document.querySelectorAll(selector)[0]
Add a class to an element
// After adding the DOM structure, there is an additional class attribute world in the class
document.querySelectorAll(".hello").forEach(d=>{
    d.classList.add("world")
})
Add css attribute
// We want to add width, height and color attributes to each element
let css = {
    "width": "2rem",
    "height": "1rem",
    "color": "red"
  }
document.querySelectorAll(".hello").forEach(d=>{
      Object.keys(css).map(k =>{
        d.style[k] = css[k];
      });
    })

The above method seems to be troublesome. It needs to be called every time. How to make it possible to call only once and make chain call like jq.

Improvement
// Get DOM element
  function $(selector) {
    return Array.from(document.querySelectorAll(selector));
  }
  // Add class
  Array.prototype.addClassName = function(className){
    this.forEach(d =>{
      d.classList.add(className);
    })
    return this;
  }

  // Add css
  Array.prototype.css = function(options){
    this.forEach(d=>{
      Object.keys(options).map(k =>{
        d.style[k] = options[k];
      });
     return this;
    })

    return this;
  }
  // Search element
  Array.prototype.eq = function(idx){
    return this[idx];
  }
jQuery initial experience
console.log($(".hello").addClassName("nihao").css({
    "width": "2rem",
    "height": "1rem",
    "color": "red"
  }).eq(2)); //Test it.

The chain call can be realized through the above operation, which is more and more like that.

We want to encapsulate more details inside the object
class JQuery{
    constructor(selector) {
      this.elements = Array.from(document.querySelectorAll(selector));
    }

    eq(index){
      return this.elements[index];
    }
    css(options){
      this.elements.forEach(d=>{
        Object.keys(options).map(k =>{
          d.style[k] = options[k];
        });
      })
      return this;
    }
    addClass(className){
      this.elements.forEach(d=>{
        d.classList.add(className);
      })
      return this;
    }
  }
More and more jQuery
console.log(new JQuery("#jq").addClass("hha").css({
  "width": "2rem",
  "height": "1rem",
  "color": "red"
}).eq(1)); // Test it.

After changing to es6 syntax for simple encapsulation, it is found that it can still be implemented, and the structure is more and more clear. In addition, there is no implementation for attr, html, text and other methods.

Posted by mike2098 on Tue, 14 Apr 2020 07:54:06 -0700