preface

Recently repackaged an in-house library of UI components, including a module that extends The Element-Plus message and makes extensive use of native DOM manipulation, The easiest way to manipulate the DOM is to use jquery, but writing a vUE component that references jquery is an insult to vue. But honestly, in these days of frameworks, how long has it been since you wrote a native JS? I’ve been writing for a long time and I’ve forgotten some of the native apis, so let’s get moving and review some of the familiar and unfamiliar apis.

Common DOM operations

Gets the find DOM element

Ele.getElementById(idName)

Find elements by ID. The DOM element is returned, and if there are multiple elements with the same ID on the page, only the first element is returned, not multiple (in principle, only one ID, but great programmers…).

Ele.getElementByClassName(className)

Find by class. It returns a class array structure, and to do forEach traversal, it needs to be converted to an array structure


const doms = document.getElementByClassName('xxx')

const domsArr = Array.from(doms)

domsArr.forEach(dom=>{})

Copy the code

Ele.getElementsByTagName(tagName)

Get the element with the tag name in the same way as getElementByClassName.

Ele.querySelector(selectors) | Ele.querySelectorAll(selectors)

These are the only apis that support the use of selectors to find elements, which makes it much easier to do deeper look-ups

<div class="warp"> <p>name<p> <p>age<p> <div> <p>... </p> <script> // Target gets p below warp 1. Don't use querySelectorAll cons warp = document. GetElementsByClassName (" warp ") [0]; const allp = warp.getElementsByTagName(p) 2. Using querySelectorAll const allp = document. QuerySelectorAll (" warp p ") < / script >Copy the code

Style the DOM

Add styles to elements

Ele.style.width = xxx

Copy the code

Add class to the element

Ele.classname ='aaa' // Set the class of the element to aaa, Add = "aaa" // add aaa Ele to Ele. ClassName += "aaa" // add AAA to EleCopy the code

Determines whether an attribute exists on an element

Ele.classlist. contains("aaa") // Returns true if Ele has aaa on it, false otherwiseCopy the code

Manipulate properties on the DOM

The new attribute

Ele.setAttribute("data-id", 1);

Copy the code

Gets the value of the property

Ele.getAttribute("data-id");

Copy the code

Delete the properties

Ele.removeAttribute("data-id");
Copy the code

Add, delete, change and search for DOM elements

Creating a DOM element

 const p = document.createElement("p");

Copy the code

Deleting DOM elements

Ele.remove(); RemoveChild (clildEle) // Delete childEle from ELeCopy the code

Copy the DOM

Ele.cloneNode( true | false ) const box = document.getElementsByClassName("box")[0]; const p = document.createElement("p"); P.innertext = "welcome attention code not stop wechat public account "; const p2 = p.cloneNode(true); Box.appendchild (p); // copy ap argument true to indicate deep replication. box.appendChild(p2);Copy the code

As shown, there are two P tags and both are displayed on the page

Inserted into the DOM

InsertBefore (newele, Ele) // Insert newele before Ele in element EleCopy the code

Replace the DOM

Parentele.replacechild (newEle,oldEle) <body> <div class="box"> <h1> <script> const btnDom = document.getElementById("btn"); const box = document.getElementsByClassName("box")[0]; const h1 = document.getElementsByTagName("h1")[0]; const h2 = document.createElement("h2"); H2. InnerText = "code never stops "; btnDom.onclick = function () { box.replaceChild(h2, h1); }; </script> </body>Copy the code

Delete the DOM

EleParent. RemoveChild (ele) // Remove ele from EleParentCopy the code

Traversing the DOM

  • parentNode

Finds the parent node of the specified node

  • nextSibling

Finds the next node of the specified node

  • previousSibling

Finds the last node of the specified node

  • firstChild

Finds the first byte point of the specified node

  • lastChild

Finds the last byte point of the specified node

  • childElementCount

Returns the number of child elements, excluding text nodes and comments

  • firstElementChild

Returns the first child element

  • lastElementChild

Returns the last child element

  • previousElementSibling

Returns the previous adjacent sibling element

  • nextElementSibling

Returns the next adjacent sibling element

Note that nodes and elements are not equal

<body> <div id="box"> <p> file </p> <p> file </p> </div> <script> const box = document.getelementById ("box"); console.log(box.firstChild); // Print the text node (newline) console.log(box. FirstElementChild); // Print p tag </script> </body>Copy the code

Determine the element node type

NodeType, a total of 12 types, see W3C

<body> <div id="box"> <p> file </p> <p> file </p> </div> <script> const box = document.getelementById ("box"); console.log(box.firstChild.nodeType); / / 3 text console. The log (box. FirstElementChild. NodeType); // 1 element </script> </body>Copy the code

Browser native event inventory

Mouse events

Event set

  • Click event
Ele.onclick = function () {
    console.log("onclick");
 };
Copy the code
  • Double-click the event
Ele.ondblclick = function () {
    console.log("ondblclick");
 };
Copy the code
  • Right click on the event
Ele.oncontextmenu = function () {
    console.log("oncontextmenu");
 };
Copy the code
  • Mouse down event
Ele.onmousedown = function () {
    console.log("onmousedown");
 };
Copy the code
  • Mouse movement event
Ele.onmousemove = function () {
    console.log("onmousemove");
 };
Copy the code
  • Mouse up event
Ele.onmouseup = function () {
    console.log("onmouseup");
 };
Copy the code
  • Mouse in event

// Mouse moves over itself trigger events, and moves over its children trigger events

Ele.onmouseover = function () {
    console.log("onmouseover");
 };
Copy the code

// Mouse moves over itself trigger events, but moves over its children do not

 Ele.onmouseenter = function () {
    console.log("onmouseenter");
 };
Copy the code
  • Mouse away event

// Mouse moves over itself trigger events, and moves over its children trigger events

Ele.onmouseout = function () {
    console.log("onmouseout");
 };
Copy the code

// Mouse moves over itself trigger events, but moves over its children do not

 Ele.onmouseleave = function () {
    console.log("onmouseleave");
 };
Copy the code

Keyboard events

Event set

Keydown: This event is triggered when the user presses any key on the keyboard, and is repeated if the user holds it down. Keypress: This event is triggered when the user presses a character key on the keyboard (that is, the keypress event is triggered when the user presses a key that outputs characters on the screen), and is repeated if held (it is also triggered when the Esc key is pressed). Keyup: Triggered when the user releases a key on the keyboard.

Move div based on keyboard events using arrow keys

<body> <div id="box"> <div id="move"> </div> </div> <script> const box = document.getelementById ("box"); const move = document.getElementById("move"); let lefts = box.style.left || 0; let tops = box.style.top || 0; document.addEventListener("keydown", function (e) { const code = e.keyCode; Move. innerHTML = "start moving "; Switch (code) {case 38: move. InnerHTML = "innerHTML "; tops -= 5; break; Case 40: move. InnerHTML = "innerHTML "; tops += 5; break; Case 37: move. InnerHTML = "left "; lefts -= 5; break; Case 39: move. InnerHTML = "innerHTML "; lefts += 5; break; default: break; } box.style.top = tops + "px"; box.style.left = lefts + "px"; }); Document. The addEventListener (" keyup ", function () {move. InnerHTML = "static"; }); document.addEventListener("keypress", function () { console.log("keypress"); }); </script> </body>Copy the code

Form events

-Leonard: Submit the form, reset the form, change the value, blur it, focus it,

window

The window event refers to the browser window itself, not the document object inside the window.

Onload: Unload is called when documents and resources have been loaded. Resize is called when the user leaves the current document and moves to another document. The browser window changes

Other events

Beforeunload: Events triggered before closing a browser window

DOMContentLoaded: An event that is triggered once the document object is loaded, without waiting for styles, images, etc

Readystatechange: Document has a readyState property to describe the loading state of document. Changing the readyState will trigger the readyStatechange event

Document. readyState === ‘complete’ page loading document.readyState === ‘loading’ page loading

PageShow and PageHide: Triggered each time a user browses a page to close

Javascript native object inventory

Time object Date

Some common methods

  • ToLocaleDateString () : Converts the Date part of the Date object to a string according to the local time format

  • ToLocaleTimeString () : Converts the time part of the Date object to a string according to the local time format

  • ToLocaleString () : Converts the Date object to a string based on the local time format

  • GetTime () : Gets the current timestamp

The timestamp is converted to time

function timestampToTime(timestamp) { if (typeof timestamp ! = "number") return false; if (timestamp.length === 10) timestamp = timestamp * 1000; const date = new Date(timestamp); Y = date.getFullYear() + "-"; M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"; D = (date.getDate() < 9 ? "0" + date.getDate() : date.getDate()) + " "; h = (date.getHours() < 9 ? "0" + date.getHours() : date.getHours()) + ":"; m = (date.getMinutes() < 9 ? "0" + date.getMinutes() : date.getMinutes()) + ":"; s = date.getSeconds() < 9 ? "0" + date.getSeconds() : date.getSeconds(); return Y + M + D + h + m + s; }Copy the code

Time is converted to timestamp

  function timeToTimestamp(time){
    const date = new Date(time);
    return date.getTime()
  }

Copy the code

The Math object

  • Math.abs() : take the absolute value

    Math.abs(-1) // 1

  • Math.ceil() : round up

    Math. Ceil (1.1) / / 2

  • Math.floor() : round down

    Math. Floor (1.1) / / 1

  • Math.round() : round

Math. Round (1.5) / / 2

  • Math.max() : take the maximum value

Math.max(1,2,3) // 3

  • Math.min() : take the minimum value

Math.min(1, 2, 3) // 1

  • Math.random() : generates a random number 0-1

Math.random()

  • Math.h pow () : the power

    Math.pow(2,3) // == 2*2*2 == 8

  • Math.sqrt() : square root

Math.sqrt(36) // 6

Author: Liu Xiaogui Link: juejin.cn/post/696606… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.