JavaScript common API collection summary

This chapter includes DOM operation, CSS operation, Object (Object object Object, Array Object, Number Object, String Ob...

This chapter includes DOM operation, CSS operation, Object (Object object Object, Array Object, Number Object, String Object, Math Object, JSON Object and Console Object) operation, which is worth collecting.
1, Node
1.1 node properties

Node.nodeName //Return node name, read-only Node.nodeType //Return constant value of node type, read-only Node.nodeValue //Returns the Text value of the Text or Comment node, read-only Node.textContent //Returns the text content of the current node and all its descendants, readable and writable Node.baseURI //Returns the absolute path of the current page Node.ownerDocument //Returns the top-level document object where the current node is located, that is, document Node.nextSibling //Returns the first sibling immediately following the current node Node.previousSibling //Returns the nearest sibling node in front of the current node Node.parentNode //Returns the parent of the current node Node.parentElement //Returns the parent Element node of the current node Node.childNodes //Returns all children of the current node Node.firstChild //Returns the first child of the current node Node.lastChild //Returns the last child of the current node //parentNode interface Node.children //Returns all Element child nodes of the specified node Node.firstElementChild //Returns the first Element child of the current node Node.lastElementChild //Returns the last Element child of the current node Node.childElementCount //Returns the number of all Element child nodes of the current node.

1.2 operation

Node.appendChild(node) //Add the last child to the node Node.hasChildNodes() //Returns a Boolean value indicating whether the current node has children Node.cloneNode(true); // The default is false (clone node), true (clone node and its attributes, and descendants) Node.insertBefore(newNode,oldNode) // Insert a new child node before specifying it Node.removeChild(node) //Delete node, operate on the parent node of the node to be deleted Node.replaceChild(newChild,oldChild) //Replace node Node.contains(node) //Returns a Boolean value indicating whether the parameter node is a descendant of the current node. Node.compareDocumentPosition(node) //Returns a binary value of 7 bits representing the relationship between the parameter node and the current node Node.isEqualNode(noe) //Returns a Boolean value that checks whether two nodes are equal. The so-called equal nodes refer to two nodes with the same type, the same attribute and the same child node. Node.normalize() //Used to clean up all Text nodes inside the current node. It removes empty Text nodes and merges adjacent Text nodes into one. //ChildNode interface Node.remove() //Used to delete the current node Node.before() // Node.after() Node.replaceWith()

1.3 Document node
1.3.1 properties of document node

document.doctype // document.documentElement //Returns the root node of the current document document.defaultView //Returns the window object where the document object is located document.body //Returns the < body > node of the current document document.head //Return the < head > node of the current document document.activeElement //Returns the element in the current document that gets the focus. //Node collection properties document.links //Returns all a elements of the current document document.forms //Return to all form elements in the page document.images //Return to all picture elements in the page document.embeds //Return to all embedded objects in the web page document.scripts //Returns all scripts for the current document document.styleSheets //Returns all style sheets for the current page //Document information properties document.documentURI //Indicates the web address of the current document document.URL //Returns the web address of the current document document.domain //Returns the domain name of the current document document.lastModified //Returns the timestamp of the last modification of the current document document.location //Returns the location object, providing the URL information of the current document document.referrer //Returns the access source of the current document document.title //Returns the title of the current document document.characterSet Property returns the character set that renders the current document, such asUTF-8,ISO-8859-1. document.readyState //Returns the status of the current document document.designMode //Control whether the current document is editable, readable and writable document.compatMode //Return to the browser's mode of processing documents document.cookie //Used to operate cookies

1.3.2 method of document node
(1) Reading and writing methods

document.open() //Use to create and open a new document document.close() //New documents created by the open method document.write() //Used to write content to the current document document.writeIn() //Used to write content to the current document, with line breaks added at the end.

(2) Find nodes

document.querySelector(selectors) //Takes a CSS selector as a parameter and returns the first element node that matches the selector. document.querySelectorAll(selectors) //Takes a CSS selector as a parameter and returns all element nodes that match the selector. document.getElementsByTagName(tagName) //Returns all elements of the specified HTML tag document.getElementsByClassName(className) //Returns all elements whose class name meets the specified criteria document.getElementsByName(name) //Used to select HTML elements with the name attribute (such as < form >, < radio >, < img >, < frame >, < embed > and < Object >) document.getElementById(id) //Returns the element node that matches the specified id attribute. document.elementFromPoint(x,y) //Returns the Element child node at the top of the page's specified location.

(3) Build node

document.createElement(tagName) //Used to generate HTML element nodes. document.createTextNode(text) //Used to generate text nodes document.createAttribute(name) //Generate a new attribute object node and return it. document.createDocumentFragment() //Generate a DocumentFragment object

(4) Event method

document.createEvent(type) //Generate an event object that can be element.dispatchEvent() method use document.addEventListener(type,listener,capture) //Register events document.removeEventListener(type,listener,capture) //Unregister Event document.dispatchEvent(event) //Trigger event

(5) Others

document.hasFocus() //Returns a Boolean value indicating whether an element in the current document is activated or focused. document.adoptNode(externalNode) //Remove a node from its original document, insert the current document, and return to the new node after insertion. document.importNode(externalNode, deep) //Copies the specified node from an external document and inserts the current document.

1.4 Element node
1.4.1 attribute of element node
(1) Property Properties

Element.attributes //Returns all attribute nodes of the current element node Element.id //Returns the id attribute of the specified element, readable and writable Element.tagName //Returns the uppercase label name of the specified element Element.innerHTML //Return the HTML code contained in the element, readable and writable Element.outerHTML //Returns all HTML code of the specified element node, including itself and all child elements contained, readable and writable Element.className //Returns the class attribute of the current element, readable and writable Element.classList //Returns all class collections of the current element node Element.dataset //Returns all data - * attributes in the element node.

(2) Dimension properties

Element.clientHeight //Returns the height of the visible part of the element node Element.clientWidth //Returns the width of the visible part of an element node Element.clientLeft //Returns the width of the left border of the element node Element.clientTop //Returns the width of the top border of an element node Element.scrollHeight //Returns the total height of an element node Element.scrollWidth //Returns the total width of an element node Element.scrollLeft //Returns the number of pixels that the horizontal scroll bar of the element node scrolls to the right. By setting this attribute, you can change the scrolling position of the element Element.scrollTop //Returns the pixel value of the element node's vertical scroll down Element.offsetHeight //Returns the vertical height of the element (including border,padding) Element.offsetWidth //Returns the horizontal width of the element (including border,padding) Element.offsetLeft //Returns the upper left corner of the current element relative to the Element.offsetParent Vertical offset of nodes Element.offsetTop //Return to horizontal displacement Element.style //Returns the inline style of an element node

(3) Node related properties

Element.children //Include all children of the current element node Element.childElementCount //Returns the number of child HTML element nodes contained in the current element node Element.firstElementChild //Returns the first Element child of the current node Element.lastElementChild //Returns the last Element child of the current node Element.nextElementSibling //Returns the next sibling HTML element node of the current element node Element.previousElementSibling //Returns the previous sibling HTML node of the current element node Element.offsetParent //Returns the closest parent element of the current element node, and the position property of CSS is not equal to static.

1.4.2 method of element node
(1) Location method

getBoundingClientRect() // getBoundingClientRect returns an object, including top,left,right,bottom,width,height // width and height elements themselves // The distance from the top outer boundary of the top element to the top of the window // The distance from the right outer boundary of the right element to the top of the window // The distance from the bottom outer boundary of the bottom element to the top of the window // The distance from the left outer boundary of the left element to the top of the window // Width element's own width (including border,padding) // Height element self height (including border,padding) getClientRects() //Returns all rectangles of the parameters of the current element on the page. // Offset of element on page var rect = el.getBoundingClientRect() return { top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft }

(2) Attribute method

Element.getAttribute(): read specified property Element.setAttribute(): set specified properties Element.hasAttribute(): returns a Boolean value indicating whether the current element node has the specified attribute Element.removeAttribute(): remove specified property

(3) Search method

Element.querySelector() Element.querySelectorAll() Element.getElementsByTagName() Element.getElementsByClassName()

(4) Event method

Element.addEventListener(): Add callback function for event Element.removeEventListener(): Remove event listener Element.dispatchEvent(): Trigger event //ie8 Element.attachEvent(oneventName,listener) Element.detachEvent(oneventName,listener) // event object var event = window.event||event; // The target node of the event var target = event.target || event.srcElement; // Event agent ul.addEventListener('click', function(event) { if (event.target.tagName.toLowerCase() === 'li') { console.log(event.target.innerHTML) } });

(5) Others

Element.scrollIntoView() //Scroll the current element to the visible area of the browser //Parse the HTML string and insert the generated node into the specified location of the DOM tree. Element.insertAdjacentHTML(where, htmlString); Element.insertAdjacentHTML('beforeBegin', htmlString); // Insert before this element Element.insertAdjacentHTML('afterBegin', htmlString); // Insert before the first child of the element Element.insertAdjacentHTML('beforeEnd', htmlString); // Insert after the last child of the element Element.insertAdjacentHTML('afterEnd', htmlString); // Insert after element Element.remove() //Used to remove the current element node from the DOM Element.focus() //Used to transfer the focus of the current page to the specified element

2, CSS operations
(1) Class name operation

//Under ie8 Element.className //Get the class name of the element node Element.className += ' ' + newClassName //Add a new class name //Determine whether there is a class name function hasClass(element,className){ return new RegExp(className,'gi').test(element.className); } //Remove class function removeClass(element,className){ element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'),''); } //ie10 element.classList.add(className) //newly added element.classList.remove(className) //delete element.classList.contains(className) //Include or not element.classList.toggle(className) //toggle class

(2) style operation

element.setAttribute('style','') element.style.backgroundColor = 'red' element.style.cssText //Used to read and write or delete the entire style property element.style.setProperty(propertyName,value) //Set css properties element.style.getPropertyValue(property) //Get css properties element.style.removeProperty(property) //Delete css attribute //Manipulate non inline styles //ie8 element.currentStyle[attrName] //ie9+ window.getComputedStyle(el,null)[attrName] window.getComputedStyle(el,null).getPropertyValue(attrName) //Pseudo class window.getComputedStyle(el,':after')[attrName]

3, Object
3.1 Object object
(1) Build instance object

var o = new Object()

(2) Properties

Object.prototype //Return prototype object

(3) Methods

Object.keys(o) //Enumerable properties of traversal objects Object.getOwnPropertyName(o) //Enumerable properties of traversal objects

Method of object instance

valueOf(): returns the corresponding value of the current object. toString(): returns the string form corresponding to the current object. toLocaleString(): returns the local string corresponding to the current object. hasOwnProperty(): determines whether a property is the property of the current object itself or inherited from the prototype object. isPrototypeOf(): determines whether the current object is a prototype of another object. propertyIsEnumerable(): determines whether a property can be enumerated.

3.2 Array object
(1) Build instance object

var a = new Array()

(2) Properties

a.length //length

(3)Array.isArray()

Array.isArray(a) //Used to determine whether a value is an array

(4) Method of Array instance

a.valueof() //Returns the array itself a.toString() //Returns the string form of an array a.push(value,vlaue....) //Used to add one or more elements at the end of an array and return the length of the array after adding new elements. pop() //Used to delete the last element of an array and return it join() //With parameters as separators, all array members are returned as a string. If no parameters are provided, they are separated by commas by default. concat() //Used for merging multiple arrays. It adds the members of the new array to the end of the original array, and then returns a new array, the original array remains unchanged. shift() //Used to delete the first element of an array and return it. unshift(value) //Used to add elements in the first position of the array and return the length of the array after adding new elements. reverse() //Used to reverse the order of elements in an array and return the changed array slice(start_index, upto_index); //Used to extract a part of the original array and return a new array. The original array remains unchanged. The first parameter is the start position (starting from 0) and the second is the end position (but the elements of that position are not included by themselves). If the second parameter is omitted, it is returned to the last member of the original array. A negative number means the last. splice(index, count_to_remove, addElement1, addElement2, ...); //It is used to delete some members of the original array and add new array members in the deleted position. The return value is the deleted element. The first parameter is the starting position of deletion, and the second parameter is the number of elements deleted. If there are more parameters later, it means that these are the new elements to be inserted into the array. sort() //Sort the array members by dictionary order by default. After sorting, the original array will be changed. If you want the sort method to sort in a custom way, you can pass in a function as a parameter to sort in a custom way. The function itself accepts two parameters, representing the two elements for comparison. If the return value is greater than 0, it means that the first element is in front of the second element; in other cases, the first element is in front of the second element. map() //Call a function to all the members of the array in turn, and return a new array according to the result of the function. map(elem,index,arr) //The map method takes a function as an argument. When this function is called, the map method passes it into three parameters, namely, the current member, the current position and the array itself. forEach() //Traverse all the members of the array, perform some operation, and the parameter is a function. It takes three parameters: the value of the current position, the number of the current position, and the entire array. filter() //Parameter is a function, all array members execute the function in turn, and the members whose return result is true form a new array to return. This method does not change the original array. some() //Used to determine whether an array member meets certain conditions. Take a function as a parameter, all array members execute the function in turn, and return a Boolean value. This function takes three parameters: the member of the current position, the sequence number of the current position, and the entire array. As long as the return value of one array member is true, the return value of the whole some method is true, otherwise false. every() //Used to determine whether an array member meets certain conditions. Take a function as a parameter, all array members execute the function in turn, and return a Boolean value. This function takes three parameters, the member of the current position, the sequence number of the current position, and the entire array. Only when the return value of all array members is true can true be returned, otherwise false. reduce() //Process each member of the array in turn, and finally accumulate to a value. Left to right (first to last member) reduceRight() //Process each member of the array in turn, and finally accumulate to a value. Right to left (from last member to first member) indexOf(s) //Returns the first occurrence of the given element in the array, or - 1 if it does not. A second parameter is acceptable, indicating where the search begins lastIndexOf() //Returns the last occurrence of the given element in the array, or - 1 if it does not.

3.3 Number object
(1) Build object

var n = new Number()

(2) Properties of the Number object

Number.POSITIVE_INFINITY: positive infinity, pointing to infinity. Number.NEGATIVE_INFINITY: negative infinity, pointing to - infinity. Number.NaN : indicates a non numeric value, pointing to Nan. Number.MAX_VALUE: indicates the maximum positive number, corresponding to which the minimum negative number is- Number.MAX_VALUE. Number.MIN_VALUE: indicates the smallest positive number (i.e. the closest positive number to 0, 5e-324 in 64 bit floating-point system), and the corresponding negative number closest to 0 is- Number.MIN_VALUE. Number.MAX_SAFE_INTEGER: represents the largest integer that can be expressed accurately, namely 900719925474091. Number.MIN_SAFE_INTEGER: represents the smallest integer that can be expressed accurately, namely - 900719925474091.

(4) Method of Number object instance

toString() //It is used to convert a numeric value into a string. It can accept a parameter to represent the base of the output. If this parameter is omitted, the value will be converted to decimal by default, and then the string will be output; otherwise, a number will be converted to a string in a certain base according to the base specified by the parameter. toFixed() //Used to convert a number to a specified number of decimal places and return the string corresponding to the decimal. toExponential() //Used to convert a number to the scientific form of counting. A parameter can be passed in. The parameter represents the number of significant digits after the decimal point. The range is 0 to 20. If the range exceeds this range, a RangeError will be thrown. toPrecision() //A valid number used to convert a number to a specified number of digits.

3.4 String object
(1) Build instance object

var s = new String()

(2) Properties of a String object

s.length //Returns the length of the string

(3) Methods

s.chatAt(index) //Returns the character at the specified location s.fromCharCode() //The parameter of this method is a series of Unicode code points, which return the corresponding string. s.charCodeAt(index) //Unicode code point returned to the anchor character (decimal representation) s.concat(s2) //Used to connect two strings s.slice(start,end) //Used to take a substring from the original string and return it without changing the original string. The first parameter is the start position of the substring, and the second parameter is the end position of the substring (excluding the position). If the parameter is a negative value, it indicates the position from the end to the reciprocal, that is, the negative value plus the string length. s.substring(start,end) //Used to take a substring from the original string and return it without changing the original string. The first parameter indicates the start position of the substring, and the second position indicates the end position. s.substr(start,length) //Used to take a substring from the original string and return it without changing the original string. The first parameter is the start position of the substring, and the second parameter is the length of the substring. If the first parameter is negative, it indicates the character position of the reciprocal calculation. If the second parameter is negative, it is automatically converted to 0, so an empty string is returned. s.indexOf(s) //Returns the first occurrence of a given element in a string, or - 1 if it does not. A second parameter is acceptable, indicating where the search begins s.lastIndexOf() //Returns the last occurrence of the given element in the string, or - 1 if it does not. s.trim() //Used to remove spaces at both ends of a string and return a new string s.toLowerCase() //Used to convert a string to lowercase and return a new string without changing the original string. s.toUpperCase() //Capitalize all s.localeCompare(s2) //Used to compare two strings. It returns an integer. If it is less than 0, it means the first string is less than the second string; if it is equal to 0, it means the two are equal; if it is greater than 0, it means the first string is greater than the second string. s.match(regexp) //It is used to determine whether the original string matches a certain substring. It returns an array with the first matching string as its member. If no match is found, null is returned. s.search() //The return value is the first location of the match. If no match is found, - 1 is returned. s.replace(oldValue,newValue) //Substring used to replace a match, typically only the first match (unless a regular expression with a g modifier is used). s.split() //Splits the string according to the given rule, and returns an array of split substrings. You can also pass in a second parameter that determines the number of members to return to the array.

3.5 Math object
(1) Properties

Math.E: constant e. Math.LN2 : the natural logarithm of 2. Math.LN10 : the natural logarithm of 10. Math.LOG2E : the logarithm of e based on 2. Math.LOG10E : the logarithm of base 10 e. Math.PI : constant Pi. Math.SQRT1_2: The square root of 0.5. Math.SQRT2 : square root of 2.

(2) Mathematical methods

Math.abs(): returns the absolute value of the parameter Math.ceil(): round up, accept a parameter, return the minimum integer greater than the parameter. Math.floor(): round down Math.max(n,n1,...): multiple parameters are acceptable, and the maximum value is returned Math.min(n,n1,..): multiple parameters are acceptable, and the minimum value is returned Math.pow(n,e): exponential operation, which returns the exponential value with the first parameter as the base and the second parameter as the power. Math.sqrt(): returns the square root of the parameter value. If the parameter is a negative value, NaN is returned. Math.log(): returns the natural logarithm value with e as the base. Math.exp(): returns the exponent of e, which is the parameter power of the constant e. Math.round(): rounding Math.random(): returns a pseudo-random number between 0 and 1, which may be equal to 0, but must be less than 1.

(3) Trigonometric function method

Math.sin(): returns the sine of the parameter Math.cos(): returns the cosine of the parameter Math.tan(): return tangent of parameter Math.asin(): returns the arcsine (radian value) of the parameter Math.acos(): returns the arccosine (radian value) of the parameter Math.atan(): returns the arctangent (radian value) of the parameter

3.6 JSON object
(1) Methods

JSON.stringify() //Used to convert a value to a string. The string should be in JSON format and can be JSON.parse Method restore. //( JSON.stringify(obj, selectedProperties)) can also accept an array as the second parameter, which specifies the property to be converted to a string. //You can also accept a third parameter to increase the readability of the returned JSON string. If it is a number, it means the space added before each attribute (no more than 10); if it is a string (no more than 10 characters), it will be added before each line. JSON.parse() //Used to convert JSON strings to objects.

3.7 console object
(1) Methods

console.log(text,text2,...) //Used to output information in the console window. It can take multiple parameters and connect their results to output. If the first parameter is a format string (using a format placeholder), console.log Method replaces the placeholder with the parameters that follow, and then outputs. console.info() //Output information in the console window, and a blue icon will be added in front of the output information. console.debug() //Output information in the console window, and a blue icon will be added in front of the output information. console.warn() //When outputting information, add a yellow triangle at the front to indicate warning; console.error() //When outputting information, add a red cross at the front to indicate an error, and the stack where the error occurred will be displayed console.table() //You can convert compound type data to table display. console.count() //For counting, output how many times it was called. console.dir() //Used to inspect an object and display it in an easy to read and print format. console.dirxml() //Used to display DOM nodes in the form of a directory tree. console.assert() //Accepts two parameters, the first being an expression and the second a string. Only when the first parameter is false will the second parameter be output, otherwise there will be no result. //These two methods are used for timing and can calculate the exact time an operation takes. console.time() console.timeEnd() //The time method indicates the start of timing, and the timeEnd method indicates the end of timing. Their argument is the name of the timer. After calling the timeEnd method, the console window displays "timer Name: elapsed time.". console.profile() //Used to create a new performance tester (profile), whose parameter is the name of the performance tester. console.profileEnd() //Used to end a running performance tester. console.group() console.groupend() //These two methods are used to group the displayed information. It is only useful when outputting a large amount of information. Information in a group can be folded / expanded with the mouse. console.groupCollapsed() //It is used to group the displayed information. The contents of this group are collapsed rather than expanded when they are displayed for the first time. console.trace() //Displays the call path of the currently executing code in the stack. console.clear() //Used to clear all output from the current console and return the cursor to the first line.

24 June 2020, 03:48 | Views: 5370

Add new comment

For adding a comment, please log in
or create account

0 comments