Collection of common JavaScript API s

Keywords: Attribute JSON Javascript less

Collection of common JavaScript API s

http://caibaojian.com/javascript-api-collection.html
A-A+
Front-end Blog 2017-03-08 Front-end Development TutorialJavaScript•859View0

This article shares some of them. JavaScript Frequently-used Code There are DOM operations, CSS Operations, objects (Object objects, Array objects, Number objects, String objects, Math objects, JSON Object and Console object) operations, worth collecting.

Original text: Common API Collection

I. node

1.1 Node Properties

Node.nodeName   //Returns the node name, read-only
Node.nodeType   //Returns the constant value of the node type, read-only
Node.nodeValue  //Returns the text value of a 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    //Return the absolute path to the current page

Node.ownerDocument  //Returns the top-level document object, document, where the current node is located.
Node.nextSibling  //Returns the first sibling node immediately behind 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 child nodes 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 subnodes of the current node.

1.2 operation

Node.appendChild(node)   //Add the last child node to the node
Node.hasChildNodes()   //Returns a Boolean value indicating whether the current node has children
Node.cloneNode(true);  // Default is false (clone node), true (clone node and its attributes, and descendants)
Node.insertBefore(newNode,oldNode)  // Insert new child nodes before specifying them
Node.removeChild(node)   //Delete the node and operate on the parent node of the node to be deleted
Node.replaceChild(newChild,oldChild)  //Replacement 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 7-bit binary value representing the relationship between the parameter node and the current node
Node.isEqualNode(noe)  //Returns a Boolean value to check whether two nodes are equal. The so-called equal node refers to two nodes of the same type, the same attributes, the same sub-nodes.
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 Document node properties

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   //Returns the < head > node of the current document
document.activeElement  //Returns the element that gets the focus in the current document.

//Node Set Properties
document.links  //Returns all a elements of the current document
document.forms  //Returns all form elements in the page
document.images  //Return all image elements in the page
document.embeds  //Returns all embedded objects in the Web page
document.scripts  //Returns all scripts for the current document
document.styleSheets  //Returns all stylesheets of the current page

//Document Information Properties
document.documentURI  //Represents the address of the current document
document.URL  //Return the address of the current document
document.domain  //Returns the domain name of the current document
document.lastModified  //Returns the last modified timestamp of the current document
document.location  //Returns the location object to provide the URL information for the current document
document.referrer  //Returns the source of access to 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 as UTF-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 the browser's mode of processing documents
document.cookie   //Used to operate Cookie

1.3.2 Document Node Method

(1) Reading and writing methods

document.open()   //Used to create and open a document
document.close()   //Documents newly created by the open method
document.write()   //Used to write content to the current document
document.writeIn()  //To write to the current document, add line breaks at the end.

(2) Finding Nodes

document.querySelector(selectors)   //Accept a CSS selector as a parameter and return the first element node that matches the selector.
document.querySelectorAll(selectors)  //Accept a CSS selector as a parameter and return all element nodes that match the selector.
document.getElementsByTagName(tagName)  //Returns all elements that specify HTML Tags
document.getElementsByClassName(className)   //Returns an element that contains all the class names that meet the specified criteria
document.getElementsByName(name)   //HTML elements with name attributes (such as < form >, < radio >, < img >, < frame >, < embedded > and < Object > etc.)
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 at the specified location.

(3) Generating nodes

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 Document Fragment object

(4) Event method

document.createEvent(type)   //Generate an event object that can be used by the element.dispatchEvent() method
document.addEventListener(type,listener,capture)  //Registration event
document.removeEventListener(type,listener,capture)  //Unregister Event
document.dispatchEvent(event)  //Trigger event

(5) Other

document.hasFocus()   //Returns a Boolean value indicating whether elements in the current document are activated or focused.
document.adoptNode(externalNode)  //Remove a node from its original document, insert the current document, and return the inserted new node.
document.importNode(externalNode, deep)   //Copy the specified node from the external document and insert the current document.

1.4 Element Node

1.4.1 Element node properties

(1) Property attributes

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 capitalized label name of the specified element
Element.innerHTML   //Returns the HTML code contained in this element, readable and writable
Element.outerHTML  //Returns all HTML code for 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 es of the current element node
Element.dataset   //Returns all data - * attributes in the element node.

(2) Size attributes

Element.clientHeight   //Returns the height of the visible part of the element node
Element.clientWidth   //Returns the width of the visible part of the 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 the element node
Element.scrollHeight  //Returns the total height of the element node
Element.scrollWidth  //Returns the total width of the element node
Element.scrollLeft   //Returns the number of pixels that the horizontal scrollbar of the element node scrolls to the right. By setting this property, the scrolling position of the element can be changed.
Element.scrollTop   //Returns the number of pixels scrolled down vertically by the element node
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 vertical offset of the top-left corner of the current element relative to the Element.offsetParent node
Element.offsetTop   //Horizontal displacement of return
Element.style  //Returns the in-line style of the element node

(3) Node-related attributes

Element.children   //Including all child elements 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 element to the current element node, and the position attribute of CSS is not equal to the parent element of static.

1.4.2 Element Node Method

(1) Position method

getBoundingClientRect()  
// getBoundingClientRect returns an object containing top,left,right,bottom,width,height // width, height element's own width.
// Distance from the top edge 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 between the outer boundary under the bottom element and the top of the window
// The distance from the left outer boundary of the left element to the top of the window
// Width element itself width (including border,padding) 
// The height element itself is high (including border,padding) 

getClientRects()   //Returns all rectangles of the current element's parameters on the page.

// The offset of elements on the page  
var rect = el.getBoundingClientRect()  
return {   
  top: rect.top + document.body.scrollTop,   
  left: rect.left + document.body.scrollLeft  
}

(2) Attribute Method

Element.getAttribute(): Read the specified properties  
Element.setAttribute(): Sets the specified properties  
Element.hasAttribute(): Returns a Boolean value indicating whether the current element node has a specified attribute  
Element.removeAttribute(): Remove the specified attribute

(3) Search method

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

(4) Event method

Element.addEventListener(): Callback functions to add events  
Element.removeEventListener(): Remove event listener function  
Element.dispatchEvent(): Trigger event

//ie8
Element.attachEvent(oneventName,listener)
Element.detachEvent(oneventName,listener)

// event object  
var event = window.event||event;    

// Target node of 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) Other

Element.scrollIntoView()   //Scroll the current element into the browser's visible area

//Parse the HTML string, and then 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 element of the element 
Element.insertAdjacentHTML('afterEnd', htmlString); // Insert after this element

Element.remove()  //Used to remove the current element node from the DOM
Element.focus()   //Used to shift the focus of the current page to the specified element

2. CSS Operation

(1) Class name operation

//ie8 below
Element.className  //Get the class name of the element node
Element.className += ' ' + newClassName  //Add a new class name

//Determine if 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)  //Does it contain
element.classList.toggle(className)  //toggle class

(2) style operation

element.setAttribute('style','')

element.style.backgroundColor = 'red'

element.style.cssText //Used to read, write, or delete the entire style attribute

element.style.setProperty(propertyName,value)  //Setting css properties
element.style.getPropertyValue(property)  //Get the css attribute
element.style.removeProperty(property)  //Delete css attributes
//Operating 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]

Three, object

3.1 Object object

(1) Generating instance objects

var o = new Object()

(2) Attributes

Object.prototype   //Returns the prototype object

(3) Method

Object.keys(o)   //Enumerable properties of traversing objects
Object.getOwnPropertyName(o)   //Traversing through non-enumerable properties of 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 form corresponding to the current object.  
hasOwnProperty(): Determines whether an attribute is an attribute of the current object itself or inherits an attribute from the prototype object. 
IsPrototype Of (): Determines whether the current object is a prototype of another object.
propertyIsEnumerable(): Determines whether an attribute is enumerable.

3.2 Array objects

(1) Generating instance objects

var a = new Array()

(2) Attributes

a.length  //length

(3)Array.isArray()

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

(4) The 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 a new element.
pop()   //Used to delete the last element of the array and return it
join()  //With parameters as delimiters, all group members are grouped into a string and returned. If no parameters are provided, commas are used by default.
concat()  //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 with the original array unchanged.
shift()  //Used to delete the first element of the array and return it.
unshift(value)  //Used to add elements at 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 part of the original array, return a new array, the original array unchanged. The first parameter is the starting position (starting from 0) and the second parameter is the terminating position (but the element of that position itself is not included). If the second parameter is omitted, it is returned to the last member of the original array. Negative numbers denote the penultimate.
splice(index, count_to_remove, addElement1, addElement2, ...);   //Used to delete a part of the original array members, and can be deleted to add a new position in the array members, the return value is deleted elements. The first parameter is the starting position of deletion, and the second parameter is the number of deleted elements. If there are more parameters later, it means that these are new elements to be inserted into the array.
sort()   //Group members are sorted by default in dictionary order. After sorting, the original array will be changed. If you want the sort method to be sorted in a custom way, you can pass in a function as a parameter to indicate that the sort is done in a custom way. The function itself accepts two parameters, representing two elements for comparison. If the return value is greater than 0, it means that the first element is behind the second element; otherwise, the first element is ahead of the second element.
map()   //A function is called to all members of the array in turn, and a new array is returned based on the result of the function.
map(elem,index,arr)   //The map method takes a function as a parameter. When the function is called, the map method passes it in three parameters, namely the current member, the current location and the array itself.
forEach()   //Traversing through all the members of the array to perform some operation, the parameter is a function. It accepts three parameters: the value of the current location, the number of the current location, and the entire array.
filter()   //The parameter is a function, which is executed by all the members of the array in turn. 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 the members of an array meet certain conditions. Accept a function as a parameter, and all members of the array execute the function in turn, returning a Boolean value. The function accepts three parameters, namely, the members of the current position, the ordinal number of the current position and the whole array. As long as the return value of an array member is true, the return value of the entire some method is true, otherwise false.
every()   //Used to determine whether the members of an array meet certain conditions. Accept a function as a parameter, and all members of the array execute the function in turn, returning a Boolean value. The function accepts three parameters, namely, the members of the current position, the ordinal number of the current position and the whole array. The return value of all group members is true before returning true, otherwise false.
reduce()   //Each member of the array is processed in turn, and eventually accumulated as a value. Processing from left to right (from the first member to the last member)
reduceRight()  //Each member of the array is processed in turn, and eventually accumulated as a value. From right to left (from last member to first member)
indexOf(s)   //Returns the location of the first occurrence of a given element in the array, and - 1 if it does not occur. The second parameter is acceptable to indicate the start of the search
lastIndexOf()  //Returns the location of the last occurrence of a given element in the array, and - 1 if it does not occur.

3.3 Number object

(1) Generating objects

var n = new Number()

(2) Properties of Number objects

Number.POSITIVE_INFINITY: Positive infinity, pointing to Infinity.  
Number.NEGATIVE_INFINITY: Negative Infinity.  
Number.NaN: Represents a non-numeric value and points to NaN.  
Number.MAX_VALUE: Represents the largest positive number, correspondingly, the smallest negative number is - Number.MAX_VALUE.  
Number.MIN_VALUE: Represents the smallest positive number (i.e. the nearest positive number to 0, 5e-324 in 64-bit floating-point system), and correspondingly, the nearest negative number to 0 is - Number.MIN_VALUE.  
Number.MAX_SAFE_INTEGER: Represents the largest integer that can be accurately represented, that is, 9007199254740991.  
Number.MIN_SAFE_INTEGER: Represents the smallest integer that can be accurately represented, that is - 9007199254740991.

(4) Method of Number Object Instance

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

3.4 String objects

(1) Generating instance objects

var s = new String()

(2) Attributes of String Objects

s.length   //Returns the length of the string

(3) Method

s.chatAt(index)   //Returns the character at the specified position
s.fromCharCode()    //The parameters of this method are a series of Unicode code code points, which return the corresponding string.
s.charCodeAt(index)    //Returns the Unicode code code code point (decimal representation) of a given position character
s.concat(s2)  //Used to connect two strings
s.slice(start,end)   //Used to extract substrings from the original string and return them 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 that position). If the parameter is negative, it represents the position of the reciprocal calculation from the end, that is, the negative value plus the length of the string.
s.substring(start,end)  //Used to retrieve the substring from the original string and return it without changing the original string. The first parameter represents the starting position of the substring, and the second position represents the ending position.
s.substr(start,length)   //Used to extract substrings from the original string and return them without changing the original string. The first parameter is the starting position of the substring, and the second parameter is the length of the substring. If the first parameter is a negative number, it represents the character position of the reciprocal calculation. If the second parameter is a negative number, it will be automatically turned to zero, thus returning an empty string.
s.indexOf(s)   //Returns the location of the first occurrence of a given element in a string, and - 1 if it does not occur. The second parameter is acceptable to indicate the start of the search 
s.lastIndexOf()  //Returns the last occurrence of a given element in a string, and - 1 if it does not occur.
s.trim()  //To remove the spaces at both ends of a string and return a new string
s.toLowerCase()  //Used to convert all strings to lowercase and return a new string without changing the original string.
s.toUpperCase()  //All capitalized
s.localeCompare(s2)  //Used to compare two strings. It returns an integer, if less than 0, which means that the first string is less than the second string; if equal to 0, it means that the two are equal; if greater than 0, it means that the first string is larger than the second string.
s.match(regexp)   //Used to determine whether the original string matches a substring, returns an array of matched first string members. If no match is found, null is returned.
s.search()  //The return value is the first position of the match. If no match is found, return - 1.
s.replace(oldValue,newValue)  //Substrings used to replace matches are typically substituted only for the first match (unless a regular expression with a g modifier is used).
s.split()  //Divide the string according to the given rule, and return an array consisting of the separated substrings. You can also pass in a second parameter, which determines the number of members returned to the array.

3.5 Math objects

(1) Attributes

Math.E: Constant e.  
The natural logarithm of Math.LN2:2.  
Math.LN10:10 natural logarithm.  
Math.LOG2E: Logarithm of e with base 2.  
Math.LOG10E: Logarithm of e with base 10.  
Math.PI: Constant Pi.  
The square root of Math.SQRT1_2:0.5.  
The square root of Math.SQRT2:2.

(2) Mathematical methods

Math.abs(): Returns the absolute value of the parameter  
Math.ceil(): Integrates upwards, accepts a parameter, and returns the smallest integer greater than that parameter. 
Math.floor(): Drop down  
Math.max(n,n1,...): Accepts multiple parameters and returns the maximum value  
Math.min(n,n1,...): Accepts multiple parameters and returns the minimum.  
Math.pow(n,e): An exponential operation that returns an 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 logarithmic value based on e.
Math.exp(): Returns the exponent of e, which is the parameter power of constant E.
Math.round(): Rounding  
Math.random(): Returns a pseudorandom 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(): Returns the tangent of the parameter  
Math.asin(): Returns the arcsine of the parameter (radian value)  
Math.acos(): Returns the inverse cosine of the parameter (radian value)  
Math.atan(): Returns the arc tangent of the parameter (radian value)

3.6 JSON Objects

(1) Method

JSON.stringify()   
//Used to convert a value to a string. The string should conform to the JSON format and can be restored by the JSON.parse method.
//(JSON.stringify(obj, selectedProperties)) can also accept an array as the second parameter, specifying properties that need to be converted to strings.
//A third parameter can also be accepted to increase the readability of the returned JSON string. If it is a number, it represents the space added before each attribute (up to 10 characters); if it is a string (no more than 10 characters), the string is added before each line.

JSON.parse()   //Used to convert JSON strings into objects.

3.7 console object

(1) Method

console.log(text,text2,...)   //Used to output information in the console window. It can accept multiple parameters and output their results together. If the first parameter is a format string (using format placeholders), the console.log method replaces the placeholders with the following parameters in turn, and then outputs them.
console.info()   //The console window outputs information, and a blue icon is added to the front of the output information.
console.debug()  //The console window outputs information, and a blue icon is added to the front of the output information.
console.warn()  //When output information, add a yellow triangle at the front to indicate warning.
console.error()  //When output information, add a red fork at the front to indicate an error and show the stack where the error occurred.
console.table()  //Composite data can be converted to tabular display.
console.count()  //For counting, output how many times it has been called.
console.dir()    //Used to inspect an object and display it in a format that is easy to read and print.
console.dirxml()  //Used to display DOM nodes in the form of a directory tree.
console.assert()  //Accept two parameters, the first is an expression, and the second is 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 spent on an operation.
console.time()
console.timeEnd()
//The time method represents the beginning of the timing, and the timeEnd method represents the end of the timing. Their parameters are the name of the timer. After calling the timeEnd method, the console window displays "Timer name: the time spent".

console.profile()  //Used to create a new performance tester (profile), whose parameters are the name of the performance tester.
console.profileEnd()  //Used to end the running performance tester.

console.group()

Posted by a-mo on Fri, 19 Apr 2019 17:45:33 -0700