JS method for selecting DOM elements /////////
Note: Native JS selects DOM elements much faster than using jquery class libraries
1. Select elements by ID /////////
document.getElementById (' myID ');
2. Select elements by Class /////////
Document.getelementsbyclassname (' MyClass ') [0];
/3, select element/////////by Tag
document.getElementsByTagName (' mydiv ') [0];
/4. Select elements by name attribute (commonly used in forms)/////////
Document.getelementsbyname (' myname ') [0];
js Modify CSS style /////////
document.getElementById (' myID '). style.display = ' None ';
js Modify class attribute ////////
document.getElementById (' myID '). ClassName = ' active ';
If there is more than one class attribute, it is separated by a space ////////
document.getElementById (' myID '). ClassName = ' Active Div-1 ';
removes all class////////on this element
document.getElementById (' myID '). ClassName = ";
/Note: Using Classlist is better than using classname////////
document.getElementById (' myID '). Classlist.item (0);//item is the index of the class name
document.getElementById (' myID '). classlist.length;//read-only property
document.getElementById (' myID '). Classlist.add (' Newclass ');//Add Class
document.getElementById (' myID '). Classlist.remove (' Newclass ');//Remove Class
document.getElementById (' myID '). Classlist.toggle (' Newclass ');//toggle, either remove, no add
document.getElementById (' myID '). Classlist.contains (' Newclass ');//Determine if the class exists
JS Modified text ////////
document.getElementById (' myID '). InnerHTML = ' 123 ';
///////// Array de-weight method /////////
Array.prototype.unique = function () {
var tem = {},//New Empty Object , add an attribute to the number not appearing in the array
arr = [],///de-this.length the array
len = *//////To make the length of the redo array
for (Var i=0;i<len;i++) {
if (! Temp[this[i]) {///determine the number in the array as the attribute name in temp there is no attribute value
temp[this[i]]= "ABC";//If there is no attribute value, then it does not appear to give him a property value
Arr.push (this[i ]);//Add this number to the array to be re-added to
}
}
return arr;///finally return this array, this is the hash algorithm
}
///////// removes duplicate elements in the array /////////
function Getunique (somearray) {
Temparray = Somearray.slice (0); Copies an array to a temporary array
for (var i = 0; i < temparray.length; i++) {
for (var j = i + 1; j < Temparray.length;) {
if (temparray[j] = = Temparray[i])
//The elements that follow are deleted and counted if they are the same as to be compared, and after the
//delete, the subsequent elements are automatically advanced, so the pointer J does not move
{
Temparray.splice (j, 1);
}
Else {
J + +;
}
//Different, the pointer moves
}
}
return temparray;
}
///////// Determines whether a value is in an array /////////
Array.prototype.in_array = function (e) {
for (i = 0; I & Lt This.length; i++) {
if (this[i] = = e)
return true;
}
return false;
}
///////// determines the position of a value in the array /////////
Array.prototype.indexOf = function (e) {
for (i = 0; i < this.length; i++) {
if (this[i] = = e)
return i;
}
Return-1;
}
/Grail mode = Inherit (inherit from him, change yourself without affecting him)/////////
function inherit (target,origin) {//target element and initial element
function F () {}; Create an intermediate function
F.prototype = Origin.prototype; The prototype of the intermediate function inherits from the original function
Target.prototype = new F (); The constructor F-target function inherits from this
Target.prototype.constructor = Target; Make the constructor of the target function point to himself
Target.prototype.uber = Origin.prototype; Store target functions in Uber where they really inherit from
}
Father.prototype.lastName = "Hui";
function Father () {}
function Son () {}
Inherit (Son,father);
var son = new son ();
var father new father ();
/////////time stamp to format time/////////
function FormatDate (timestamp, formats) {
/*
The formats format includes
1. y-m-d
2. y-m-d h:m:s
3. Y year M month D Day
4. Y year M D Day h M min
5. Y year M month D Day h M min s second
Example: Console.log (FormatDate (1500305226034, ' Y year m D h:m:s ')) ==> July 17, 2017 23:27:06
*/
formats = Formats | | ' Y-m-d ';
var mydate = timestamp? New Date (timestamp): new Date ();
var year = Mydate.getfullyear ();
var month = Formatdigit (Mydate.getmonth () + 1);
var day = Formatdigit (Mydate.getdate ());
var hour = Formatdigit (Mydate.gethours ());
var minute = Formatdigit (Mydate.getminutes ());
var second = Formatdigit (Mydate.getseconds ());
Return Formats.replace (/y| m| d|h|m|s/g, function (matches) {
Return ({
Y:year,
M:month,
D:day,
H:hour,
M:minute,
S:second
}) [matches];
});
Less than 10 complement 0
function Formatdigit (n) {
Return n.tostring (). Replace (/^ (\d) $/, ' 0$1 ');
};
}
thousand-bit display, commonly used for price display /////////
function Tothousands (num) {
return parsefloat (num). toFixed (2). Replace (/(\d{1,3}) (? = (\d{3}) + (?: \.)) /g, "$,");
}
JS get page address parameter /////////
function GetParameter (param) {
var query = window.location.search;//Gets the URL address? After all the characters
var Ilen = param.length;//Get your parameter name length
var iStart = query.indexof (param);//Get you the index of the parameter name in fact
if (IStart = =-1)//-1 is not the parameter
Return "";
IStart + = Ilen + 1;
var iend = Query.indexof ("&", IStart);//Get the fact index of the second argument
if (iend = =-1)//Only one parameter
Return query.substring (IStart);//Gets the parameter value of a single parameter
Return query.substring (IStart, iend);//Gets the value of the second parameter
}
Judging whether the number /////////
function IsNumeric (TXT) {
if (txt = = "") {
return false;
}
if (Txt.indexof (",") > 0) {
txt = txt.replace (",", "");
}
if (IsNaN (TXT)) {
return false;
}
else {
return true;
}
}
Set Cookie/////////
function Setcookie (name, value)//two parameters, one is the name of the cookie, and the other is the value
{
var days = 30; This cookie will be saved for 30 days
var exp = new Date (); New Date ("December 31, 9998");
Exp.settime (Exp.gettime () + days * 24 * 60 * 60 * 1000);
Document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring () + ";d omain=77tianqi.com;"
}
Read cookies
function GetCookie (name)
{
var arr = Document.cookie.match (New RegExp ("(^|)" + name + "= ([^;] *)(;|$)"));
if (arr! = null) return unescape (arr[2]); return null;
}
Delete Cookies
function Delcookie (name)
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval=getcookie (name);
if (cval!=null)
document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}
the use of the/jquery trim () function /////////
Recordlist = $.trim (recordlist);
Buffer Picture Loading effect
$ ("#loading", Navtab.getcurrentpanel ()). Ajaxstart (function () {
$ (this). Show ();
}). Ajaxcomplete (function () {
$ (this). Hide ();
});
returns the actual length of the string, a Chinese character is counted 2 lengths /////////
String.prototype.strlen = function () {
Return This.replace (/[^\x00-\xff]/g, "* *"). Length;
}
The string exceeds the ellipsis /////////
String.prototype.cutstr = function (len) {
var restr = this;
var wlength = This.replace (/[^\x00-\xff]/g, "* *"). Length;
if (Wlength > Len) {
for (var k = len/2; k < this.length; k++) {
if (This.substr (0, k). Replace (/[^\x00-\xff]/g, "* *"). Length >= len) {
Restr = This.substr (0, K) + "...";
Break
}
}
}
return restr;
}
/////////add to Favorite folder/////////
function Addfavorite (sURL, Stitle) {
try {
Window.external.addFavorite (sURL, Stitle)
} catch (e) {
try {
Window.sidebar.addPanel (Stitle, sURL, "")
} catch (e) {
Alert ("Add to collection failed, please use ctrl+d for adding")
}
}
}
/////////Set as homepage////////
function setHomePage (homeurl) {
if (document.all) {
document.body.style.behavior = ' url (#default #homepage) ';
Document.body.setHomePage (Homeurl)
} else if (Window.sidebar) {
if (Window.netscape) {
try {
Netscape.security.PrivilegeManager.enablePrivilege ("Universalxpconnect")
} catch (e) {
Alert ("The action is rejected by the browser, if you want to enable the feature, enter About:config in the Address bar, and then set the item Signed.applets.codebase_principal_support value to True");
}
}
var prefs = components.classes[' @mozilla. Org/preferences-service;1 '].getservice ( Components.interfaces.nsIPrefBranch);
Prefs.setcharpref (' Browser.startup.homepage ', Homeurl)
}
}
cross-browser bound event ////////
function Addeventsamp (obj, evt, fn) {
if (!otarget) {return;}
if (Obj.addeventlistener) {
Obj.addeventlistener (EVT, FN, false);
} else if (obj.attachevent) {
Obj.attachevent (' on ' + evt, FN);
} else {
Otarget["on" + sevttype] = fn;
}
}
/cross-browser Delete event ////////
function delevt (obj, evt, fn) {
if (!obj) {return;}
if (Obj.addeventlistener) {
Obj.addeventlistener (EVT, FN, false);
} else if (otarget.attachevent) {
Obj.attachevent ("on" + evt, FN);
} else {
Obj["on" + evt] = fn;
}
}
determine if mobile device access ////////
function Ismobileuseragent () {
Return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test ( Window.navigator.userAgent.toLowerCase ()));
}
////////Get page Height////////
function Getpageheight () {
var g = document, A = G.body, F = g.documentelement, d = g.compatmode = = "Backcompat"? A:g.documentelement;
Return Math.max (F.scrollheight, A.scrollheight, d.clientheight);
}
////////Get page Width////////
function Getpagewidth () {
var g = document, A = G.body, F = g.documentelement, d = g.compatmode = = "Backcompat"? A:g.documentelement;
Return Math.max (F.scrollwidth, A.scrollwidth, d.clientwidth);
}
////////Get page ScrollLeft////////
function Getpagescrollleft () {
var a = document;
return A.documentelement.scrollleft | | A.body.scrollleft;
}
////////Get page scrolling distance////////
function Getscrolloffset () {
if (Window.pagexoffset) {
return{
X:window.pagexoffset;
Y:window.pageyoffset
}
}ELSE{//IE8 and below
return{
X:document.body.scrollleft+document.documentelement.scrollleft;
Y:document.body.scrolltop+document.documentelement.scrolltop;
}
}
}
Gets the width and height of the form's visible range ////////
function Getviewportoffset () {
if (window.innerwidth) {
return{
X:window.innerwidth;
Y:window.innerheight
}
}ELSE{//IE8 and below
if (Document.compatmode = = "Backcompat") {//If it is weird mode, promiscuous mode
return{
X:document.body.clientwidth;
Y:document.body.clientheight;
}
}else{
return {
x:document.documentelement.clientwidth;//Standard Mode
Y:document.documentelement.clientheight
}
}
}
}
View the geometry dimensions of an element ////////
Domele.getboundingclientrect ();//6 value left top right bottom width height is not real-time monitoring
view the visual dimensions of an element //////
Div.offsetwidth
Div.offsetheight
Div.offsetleft//Returns the coordinates of the document for the non-locating parent set, returning the coordinates of the relative nearest positioned parent set for the positioned parent set
Div.offsettop
Div.offsetparent//Returns the most recently positioned parent set
returns the coordinates of an element in the document //////
function Getelmentposition (DIV) {
if (div.offsetparent = = body) {
return {
X:div.offsetleft;
Y:div.offsettop
}
}else{
}
}
let the scroll bar scroll //////
ScrollTo ();//scroll to XXX
Scrollby ();//cumulative rolling xxxx
inline style-can be written to ///////
Div.style.width//must be written in CSS style, get it in style
div.style.cssfloat//Floating
window.getComputedStyle (Div,null)//return calculated styles are computed, no relative units, read-only
window.getComputedStyle (div,null). Width
window.getComputedStyle (Div, "after")//Get a pseudo-element style sheet
Ele.currentstyle//ie dedicated, get display display style, read only
Ele.currentStyle.width
Get style properties //////
function GetStyle (elem,prop) {
if (window.getComputedStyle) {
Return window.getComputedStyle (Elem,null) [prop];
}else{
return Elem.currentstyle[prop];
}
}
////////random number time stamp////////
function UniqueId () {
var a = Math.random, B = parseint;
Return number (new Date ()). ToString () + B (Ten * A ()) + B (Ten * A ()) + B (Ten * A ());
}
/////////Match Domestic phone number (0511-4405222 or 021-87888822)////////
function Istell (str) {
var result = Str.match (/\d{3}-\d{8}|\d{4}-\d{7}/);
if (result = = null) return false;
return true;
}
////////Match ID(15-bit or 18-bit)////////
function Isidcardno (num) {
num = Num.touppercase ();
The ID number is 15 or 18 bits, 15 digits are all digits, 18 bits is the first 17 digits, the last one is the check digit, possibly the number or the character X.
if (! ( /(^/d{15}$) | (^/d{17} ([0-9]| X) $)/.test (num)))
{
Alert (' Enter the wrong ID number, or the number does not meet the rules! /n15 digits should be all numbers, the 18-digit number can be the number or X. ‘);
return false;
}
}
////////Mobile////////
function Checkmobile (str) {
if (! ( /^1[3|5|8][0-9]\d{4,8}$/.test (str))) {
return false;
}
return true;
}
////////determine if the input is a valid e-mail////////
function Isemail (str) {
var result = Str.match (/^\w+ (-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ ((\.| -) [a-za-z0-9]+] *\. [a-za-z0-9]+$/];
if (result = = null) return false;
return true;
}
//////splitting integers and decimals///////
function splits (tranvalue) {
var value = new Array (', ');
temp = Tranvalue.split (".");
for (var i = 0; i < temp.length; i++) {
Value = temp;
}
return value;
}
////////JS Create elements and append text to them////////
var newdiv = document.createelement (' div ');
var NewText = document.createTextNode (' 123 ');
Newdiv.appendchild (NewText);
Document.body.appendChild (NEWDIV);
Similarly: removechild () removes the node and returns the node////////
CloneNode ()//Replication node
InsertBefore ()//Insert node (front of parent node content)
Note: InsertBefore () has two parameters, the first one is the inserted node, the second is the inserted position
Example:
var list = document.getElementById (' myList ');
List.insertbefore (Newitem,list.childnodes[1]);
Insert a new node newitem to the second child node of the list
insertafter//////
Element.prototype.insertAfter = function (Targetnode,afternode) {
var beforenode = afternode.nextelementsibling;
if (Beforenode = = null) {
Afternode.appendchild (TargetNode);
}else{
This.insertbefore (Targetnode,beforenode);
}
}
Common JS Tool functions