(Transferred from public account: front end 8:30, authorized)

preface

With the rise of MV* frameworks and the transition from slash-and-burn to engineering, Facebook arrived with the React framework before Angular could be learned. Soon, vue. Js stood out in the heat of these frameworks, and various frameworks filled our visual nerves. It seems that the idea of manipulating the DOM to write a front end is dead. JQuery as the main front-end er library in that era, the convenience of adding, deleting, changing and checking DOM makes us worship jQuery. JQuery was born to simplify JS, but died because of simplifying JS. It has been 11 years since the first edition of jQuery was released.

The first version of jQuery was created in 2006 to simplify DOM manipulation and reduce cross-browser issues during development.

Its founder, John Resig, annotated the code, and you can find the source code for the first version of jQuery below. Genius. It/johnresig. C…

JQuery is great, but many compatibility issues have already been resolved by browsers since we don’t need IE6 and IE7 compatibility anymore, so removing jQuery from your site is the right thing to do. Js is much cleaner now, and for many DOM operations, writing in native JS is much simpler.

JQuery quick reference

1. Execute after loading the document:

$(document).ready(function$(() {})function() {})Copy the code

2. JQuery event binding on, bind, live, delegate

3. JQuery add, delete, modify and check

Add: append() – prepend() – at the end of the selected element prepend() – at the beginning of the selected element after() – appendTo() – appends all matching elements to the specified set of elements.

Remove: remove() – Removes the selected element (and its children)

$("p").remove(".italic");
Copy the code

Empty () – Removes child elements from the selected element

$("#div1").empty();
Copy the code

Modify: Sets the content – text(), HTML (), and val() text() – sets or returns the text content of the selected element

$("#test1").text("Hello world!");
Copy the code

HTML () – Sets or returns the content of the selected element (including HTML tags)

$("#test2").html("Hello world!");
Copy the code

Val () – Sets or returns the value of the form field

$("#test3").val("Dolly Duck");
Copy the code

The jQuery attr() method is also used to set/change property values. Attr sets multiple values

$("#w3s").attr({
    "href" : "http://www.w3school.com.cn/jquery"."title" : "W3School jQuery Tutorial"
});
Copy the code

Get: Get the content – text(), HTML () and val() Bold text TEXT () – Sets or returns the text content of the selected element HTML () – sets or returns the content of the selected element (including HTML tags) Val () – sets or returns the value of the form field

– attr() The jQuery attr() method is used to get the value of an attribute

$("#w3s").attr("href")
Copy the code

Search: 1. Basic filter: a) :first, select the first element, don’t forget that it is also placed in a set oh! Because JQuery is a collection of DOM objects. For example, “$(” tr:first”) “returns the first tr element of all tr elements, which is still stored in the collection.

B) : select the last element. For example, “$(” tr:last”) “returns the last tr element of all tr elements, which is still stored in the collection.

C):even, :odd Odd filter

D):not select all elements that do not match

E):eq Selects elements matched by the index

2. Child element filter :first-child (:last-child) selects the first (last) child of all parent elements. :first-of-type (:last-of-type) selects the first (last) sibling of all the same element names :nth-child(n) selects the NTH child of all their parent elements. :nth-last-child(n) selects the NTH child of all their parent elements. Count from the last element to the first. :nth-of-type(n) Selects the NTH child element belonging to the same parent element with the same tag name. Find (selector) finds all of the children of that node. Children (selector) finds all of the children, but this method only returns the direct children, not all of the children

Parent (selector) finds the parent element, which can be filtered by passing in a selector. Parents (selector) finds all the parent nodes

The siblings() filter looks for all siblings of the node. Prev () finds the node’s last sibling prevAll() finds all nodes before it next() finds the node’s next sibling nextAll() finds all nodes after it

Removing DOM dependencies

How to remove jQuery dependencies in a project, and how to use native JS instead of jQuery methods? GetElementById () is the fastest way to access the DOM. Most browsers support getElementsByClassName(). GetElementById () is the fastest way to access the DOM. The above two methods are fast, but have limited utility due to the limitation of selecting elements only by class name.

// Polyfill, implement getElementsByClassNamefunction getElementsByClassName(className) {
    var all = document.all ? document.all : document.getElementsByTagName(The '*');
    var elements = new Array();
    for (var e = 0; e < all.length; e++) {
        if (all[e].className == className) {
            elements[elements.length] = all[e];
            break; }}return elements;
}
Copy the code

QuerySelector () and querySelectorAll() : Matches the first child (all elements) of the specified CSS selector element. Note: querySelectorAll get is an Array class, can through the Array. The prototype. Slice. The call () class Array into an Array.

// Jquery selector is partially implemented with the optional container parameterfunction $(selector, container) {
  return(container || document).querySelectorAll(selector); } // Get a matching elementfunction $one(selector, container) {
  return (container || document).querySelector(selector);
}
Copy the code

GetElementsByTagName: Find elements by tag name, a safe and fast way to get an array of classes across browsers.

ParentNode: childNode, firstChild, lastChild: nextSibling, previousSibling

// Get all sibling elementsfunction getSiblings(el, filter) {
    var siblings = [];
    el = el.parentNode.firstChild;
    do { if(! filter || filter(el)) siblings.push(el); }while (el = el.nextSibling);
    return siblings;
}
Copy the code

Closest ancestor element to the current element matching specific selectors – Closest ()

// Polyfill, incompatible with browser implementations of this.element &&function(ElementPrototype) {
    ElementPrototype.closest = ElementPrototype.closest ||
        function(selector) {
            var el = this;
            while(el.matches && ! el.matches(selector)) el = el.parentNode;return el.matches ? el : null;
        }
}(Element.prototype);
Copy the code

Matches (): The element.matches () method returns true if the Element is selected by the specified selector string; Otherwise return false.

//polyfill
if(! Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while(--i >= 0 && matches.item(i) ! == this) {}return i > -1;           
        };
}
Copy the code

Create DOM-createElement replace DOM-replaceChild remove DOM (remove the parent element from the DOM, leaving the contents of the element intact)

*/ var element = document.querySelector('.container'); Var parent = element.parentNode; // Iterate to remove all child elements from this elementwhile(element.firstChild) parent.insertBefore(element.firstChild, element); // Remove the element parent.removechild (element); Empties the element's contents - removes all child nodes of the element from the DOM. var el = document.querySelector('div'); // Empty all child nodes el.innerhtml = by setting innerHTML to empty' '; Remove the DOM- the removeChild method removes a child node from the DOM. Returns the deleted node. Parent-removechild (child); // removeChild from parent. InsertBefore (dom-insertbefore, node1); //insert child before node1; //appendChild, insert the child node at the end of the parent.Copy the code

Get the element’s text content -textContent, innerText (IE8)

let node = document.querySelector('container');
let text = node.textContent || node.innerText;
Copy the code

Get/set the HTML content of the element -innerHTML property copies the current node (or copies the current node and all its descendants) -cloneNode()

4. Attribute manipulation – The ability to get and set the DOM attributes of an element

Native JavaScript provides direct access to elements’ attributes, such as href, title, Alt, and value, using the delete keyword

var node = document.querySelector('selector'); // Set property node.property =' '// Use delete to delete property property delete node.property; Add, remove, and test class // to determine whether node has a classNamefunction hasClass(node, className) {
    return node.classList ?
        node.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(node.className); } // Add classfunction addClass(node, className) {
    if (node.classList) {
        node.classList.add(className);
    }
    else if(! hasClass(node, className)) { node.className +=' '+ className; }} // Remove classfunction removeClass(node, className) {
    if (node.classList) {
        node.classList.remove(className);
    }
    else {
        node.className = node.className.replace(new RegExp('\\b' + className + '\\b'.'g'), ' '); }}Copy the code

Get, set, and delete attributes -getAttribute, setAttribute, removeAttribute

let node = document.querySelector('selector'); // Set myProp on node to myData Node.setAttribute ('myProp'.'mydata'); // Get the myProp attribute console.log(node.getAttribute('myProp')); // Remove myProp attribute Node.removeAttribute ('myProp');
Copy the code

5. Get the Settings element style

Style Fetch -getComputedStyle (IE9 below :currentStyle)

var node = document.querySelector('selector'); Var style = window.getcomputedStyle? getComputedStyle(node, null) : node.currentStyle;Copy the code

Style Settings – style, cssText

function setCss(node, styles) {
    for (var property instyles){ node.style[property] = styles[property]; } // With cssText you can set multiple styles at the same time node.style.csstext +='color:red; '
Copy the code

-scrollTop, scrollLeft gets the element’s offset position relative to its parent -offsetLeft, offsetTop gets the element’s position relative to the document’s element -getBoundingClientRect

function offset(node) {
  let rect = node.getBoundingClientRect(),
  scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}
Copy the code

Get the width and height of the element – according to the box model, the element contains margin, border, padding, content (width+height) OffsetWidth/offsetHeight access content + padding: clientWidth/clientHeight gain margin, border, padding values can be getComputedStyle For window wide high: window. InnerWidth, window. The innerHeight for document wide high: the document. The documentElement clientWidth/Height,

6. Native Ajax GET and POST requests

function getRequest(url, success) {
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.open('GET', url);
    xhr.onreadystatechange = function () {
        if (xhr.readyState > 3 && xhr.status == 200) success(xhr.responseText);
    };
    xhr.setRequestHeader('X-Requested-With'.'XMLHttpRequest');
    xhr.send();
    return xhr;
}
function postRequest(url, data, success) {
    var params = typeof data == 'string' ? data : Object.keys(data).map(
        function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
    ).join('&');
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xhr.open('POST', url);
    xhr.onreadystatechange = function() {
        if(xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }}; xhr.setRequestHeader('X-Requested-With'.'XMLHttpRequest');
    xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
    xhr.send(params);
    return xhr;
}
Copy the code

Load JS asynchronously, and the async or defer keywords can also be asynchronous

//1. Load asynchronously by dynamically inserting script tagslet scriptNode = document.createElement('script'),
  htmlNode = document.getElementsByTagName('script') [0]; scriptNode.src = url; scriptNode.parentNode.insertBefore(scriptNode, htmlNode); //2. Load <script SRC = asynchronously via the async and defer properties"" async defer></script>
Copy the code

7. Native events prevent bubbling:

window.event? window.event.cancelBubble = true : e.stopPropagation();
Copy the code

Prevent default events:

window.event? window.event.returnValue = false : e.preventDefault();
Copy the code

Get keyboard click:

var key = window.event ? event.keyCode : event.which;
console.log(key);
Copy the code

Get mouse click position:

function handler(event) {
    event = event || window.event;
    let pageX = event.pageX;
    let pageY = event.pageY;
    // IE 8
    if (pageX === undefined) {
        pageX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        pageY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    return {
        pageX:pageX,
        pageY:pageY
    }
}
Copy the code

Event binding and unbinding:

// Add eventsfunction addEvent(node, type, handler) {
    if (node.attachEvent) {
        node.attachEvent('on'+type, handler);
    } else {
        node.addEventListener(type, handler); }} // Unbindfunction removeEvent(node, type, handler) {
    if (node.detachEvent) {
        node.detachEvent('on'+type, handler);
    } else {
        node.removeEventListener(type, handler); }}Copy the code

Document loading event:

/ / corresponds to the $(document) ready () the native implementation of the document. The addEventListener ('DOMContentLoaded'.function() {});Copy the code

(end)