The related JS implementation method of jquery attribute

Source: Internet
Author: User
Tags extend join json prev trim hasownproperty


Some companies do not use a third party of jquery or Zeptio to develop their mobile web sites directly using native JavaScript. Native JavaScript functionality is quite powerful, except that some properties do not support IE8 of the following browsers. The following jquery related methods, how to use JS to achieve, do some simple summary.

Element actions

ADD Class

Jquery
$ (EL). addclass (ClassName);

Js
Google Browser, Firefox browser, ie8+
if (el.classlist)
El.classList.add (ClassName);
Else
El.classname + = ' + className;
Google Browser, Firefox browser, ie10+
El.classList.add (ClassName);
After

Jquery
$ (EL). After (htmlstring);

JS Google browser, Firefox browser, ie8+
el.insertadjacenthtml (' Afterend ', htmlstring);
Append

Jquery
$ (parent). Append (EL);

JS Google browser, Firefox browser, ie8+
Parent.appendchild (EL);
Before

Jquery
$ (EL). Before (htmlstring);

JS Google browser, Firefox browser, ie8+
el.insertadjacenthtml (' Beforebegin ', htmlstring);
Children

Jquery
$ (EL). Children ();

Js
Google Browser, Firefox browser, ie8+
var children = [];
for (var i = el.children.length; i--;) {
Skip comment nodes on IE8
if (El.children[i].nodetype!= 8)
Children.unshift (El.children[i]);
}
Google Browser, Firefox browser, ie9+
El.children
Clone

Jquery
$ (EL). Clone ();

Google Browser, Firefox browser, ie8+
El.clonenode (TRUE);
Contains

Jquery
$.contains (el, child);

Google Browser, Firefox browser, ie8+
El!== Child && el.contains (child);
Contains Selector

Jquery
$ (EL). Find (selector). length;

Google Browser, Firefox browser, ie8+
El.queryselector (selector)!== null
each

Jquery
$ (selector). Each (function (i, EL) {

});

JS Google browser, Firefox browser, ie8+
function foreachelement (selector, fn) {
var elements = Document.queryselectorall (selector);
for (var i = 0; i < elements.length; i++)
FN (Elements[i], i);
}

Foreachelement (selector, function (el, i) {

});
JS Google browser, Firefox browser, ie9+
var elements = Document.queryselectorall (selector);
Array.prototype.forEach.call (Elements, function (el, i) {

});
Empty

Jquery
$ (EL). empty ();

JS Google browser, Firefox browser, ie8+
while (El.firstchild)
El.removechild (El.firstchild);
JS Google browser, Firefox browser, ie9+
el.innerhtml = ';
Filtered Filter Filter

Jquery
$ (selector). filter (FILTERFN);

Google Browser, Firefox browser, ie8+
function filter (selector, FILTERFN) {
var elements = Document.queryselectorall (selector);
var out = [];
for (var i = elements.length; i--;) {
if (FILTERFN (Elements[i]))
Out.unshift (Elements[i]);
}
return out;
}

Filter (selector, FILTERFN);
Google Browser, Firefox browser, ie9+
Array.prototype.filter.call (Document.queryselectorall (selector), FILTERFN);
Find child elements

Jquery
$ (EL). Find (selector);

Google Browser, Firefox browser, ie8+
El.queryselectorall (selector);
Find, Selector

Jquery
$ ('. My #awesome selector ');

Google Browser, Firefox browser, ie8+
Document.queryselectorall ('. My #awesome selector ');
Get property value attr

Jquery
$ (EL). attr (' TabIndex ');

Google Browser, Firefox browser, ie8+
El.getattribute (' TabIndex ');
Get HTML content

Jquery
$ (EL). html ();

Js
El.innerhtml
Get CSS Styles

Jquery
$ (EL). CSS (RuleName);

Google Browser, Firefox browser, ie9+
getComputedStyle (EL) [RuleName];
Get text content

Jquery
$ (EL). Text ();

Google Browser, Firefox browser, ie8+
el.textcontent | | El.innertext
Google Browser, Firefox browser, ie9+
El.textcontent
Has Class

Jquery
$ (EL). Hasclass (ClassName);

Google Browser, Firefox browser, ie8+
if (el.classlist)
El.classList.contains (ClassName);
Else
New RegExp (' (^|) ' + ClassName + ' (|$) ', ' GI '). Test (El.classname);
Google Browser, Firefox browser, ie10+
El.classList.contains (ClassName);
Element comparison

Jquery
$ (EL). Is ($ (otherel));

Js
el = = = Otherel
Compare class name

Jquery
$ (EL). Is ('. My-class ');

Google Browser, Firefox browser, ie8+
var matches = function (el, selector) {
var _matches = (el.matches | | el.matchesselector | | el.msmatchesselector | | el.mozmatchesselector | | el.webkitMatchesSele ctor | | El.omatchesselector);

if (_matches) {
Return _matches.call (el, selector);
} else {
var nodes = El.parentNode.querySelectorAll (selector);
for (var i = nodes.length; i--;) {
if (nodes[i] = = EL)
return true;
}
return false;
}
};

Matches (El, '. My-class ');
Google Browser, Firefox browser, ie9+
var matches = function (el, selector) {
Return (el.matches | | el.matchesselector | | el.msmatchesselector | | el.mozmatchesselector | | el.webkitmatchesselector | | El.omatchesselector). Call (El, selector);
};

Matches (El, '. My-class ');
Next

Jquery
$ (EL). Next ();

Google Browser, Firefox browser, ie8+
NextSibling can include text nodes
function Nextelementsibling (EL) {
do {el = el.nextsibling.} while (El && el.nodetype!== 1);
Return el;
}

el.nextelementsibling | | Nextelementsibling (EL);
Google Browser, Firefox browser, ie9+
El.nextelementsibling
Offset

Jquery
$ (EL). Offset ();
JS Google browser, Firefox browser, ie8+
var rect = El.getboundingclientrect ()

{
Top:rect.top + Document.body.scrollTop,
Left:rect.left + document.body.scrollLeft
}
Outer Width

Jquery
$ (EL). Outerwidth ();
Js
El.offsetwidth
Parent

Jquery
$ (EL). Parent ();
Js
El.parentnode
Position

Jquery
$ (EL). Position ();
Js
{left:el.offsetLeft, Top:el.offsetTop}
Prev

Jquery
$ (EL). Prev ();
Google Browser, Firefox browser, ie8+
Prevsibling can include text nodes
function Previouselementsibling (EL) {
do {el = el.previoussibling.} while (El && el.nodetype!== 1);
Return el;
}

el.previouselementsibling | | Previouselementsibling (EL);
Google Browser, Firefox browser, ie9+
El.previouselementsibling
Remove

Jquery
$ (EL). Remove ();
JS Google browser, Firefox browser, ie8+
El.parentNode.removeChild (EL);
Remove Class

Jquery
$ (EL). Removeclass (ClassName);
JS Google browser, Firefox browser, ie8+
if (el.classlist)
El.classList.remove (ClassName);
Else
El.classname = El.className.replace (New RegExp (' (^|\\b) ' + classname.split ('). Join (' | ') + ' (\\b|$) ', ' GI ');

Google Browser, Firefox browser, ie10+
El.classList.remove (ClassName);
Replace from Html

Jquery
$ (EL). ReplaceWith (string);
Google Browser, Firefox browser, ie8+
el.outerhtml = string;
Set Attributes

Jquery
$ (EL). attr (' TabIndex ', 3);
Google Browser, Firefox browser, ie8+
El.setattribute (' TabIndex ', 3);
Set Html

Jquery
$ (EL). HTML (string);
Google Browser, Firefox browser, ie8+
el.innerhtml = string;
Set Style

Jquery
$ (EL). css (' border-width ', ' 20px ');
Google Browser, Firefox browser, ie8+
Use a class if possible
El.style.borderWidth = ' 20px ';
Set Text

Jquery
$ (EL). Text (string);
Google Browser, Firefox browser, ie8+
if (el.textcontent!== undefined)
El.textcontent = string;
Else
El.innertext = string;
Google Browser, Firefox browser, ie9+
El.textcontent = string;
Siblings

Jquery
$ (EL). siblings ();
Google Browser, Firefox browser, ie8+
var siblings = Array.prototype.slice.call (El.parentNode.children);

for (var i = siblings.length; i--;) {
if (siblings[i] = = EL) {
Siblings.splice (i, 1);
Break
}
}
Google Browser, Firefox browser, ie9+
Array.prototype.filter.call (El.parentNode.children, function (child) {
Return to child!== el;
});
Toggle Class

Jquery
$ (EL). Toggleclass (ClassName);
Google Browser, Firefox browser, ie8+
if (el.classlist) {
El.classList.toggle (ClassName);
} else {
var classes = El.className.split (');
var existingindex =-1;
for (var i = classes.length; i--;) {
if (classes[i] = = className)
Existingindex = i;
}

if (existingindex >= 0)
Classes.splice (Existingindex, 1);
Else
Classes.push (ClassName);

El.classname = Classes.join (");
}
Google Browser, Firefox browser, ie9+
if (el.classlist) {
El.classList.toggle (ClassName);
} else {
var classes = El.className.split (');
var existingindex = Classes.indexof (className);

if (existingindex >= 0)
Classes.splice (Existingindex, 1);
Else
Classes.push (ClassName);

El.classname = Classes.join (");
}
Google Browser, Firefox browser, ie10+
El.classList.toggle (ClassName);
Event

Off

Jquery
$ (EL). Off (EventName, EventHandler);

Google Browser, Firefox browser, ie8+
function RemoveEventListener (EL, EventName, handler) {
if (El.removeeventlistener)
El.removeeventlistener (EventName, handler);
Else
El.detachevent (' on ' + EventName, handler);
}
RemoveEventListener (EL, EventName, Handler);

Google Browser, Firefox browser, ie9+
El.removeeventlistener (EventName, EventHandler);
On

Jquery
$ (EL). On (EventName, EventHandler);

Google Browser, Firefox browser, ie8+
function AddEventListener (EL, EventName, handler) {
if (El.addeventlistener) {
El.addeventlistener (EventName, handler);
} else {
El.attachevent (' on ' + eventName, function () {
Handler.call (EL);
});
}
}

AddEventListener (EL, EventName, Handler);

Google Browser, Firefox browser, ie9+
El.addeventlistener (EventName, EventHandler);
Ready

Jquery
$ (document). Ready (function () {

});

Google Browser, Firefox browser, ie8+

Function Ready (FN) {
if (document.readystate!= ' loading ') {
FN ();
else if (Document.addeventlistener) {
Document.addeventlistener (' domcontentloaded ', FN);
} else {
Document.attachevent (' onreadystatechange ', function () {
if (document.readystate!= ' loading ')
FN ();
});
}
}

Google Browser, Firefox browser, ie9+

Function Ready (FN) {
if (document.readystate!= ' loading ') {
FN ();
} else {
Document.addeventlistener (' domcontentloaded ', FN);
}
Specify Event Trigger

Jquery
$ (EL). Trigger (' my-event ', {some: ' data '});


JS Google browser, Firefox browser, ie9+
if (window. Customevent) {
var event = new Customevent (' my-event ', {detail: {some: ' Data '}});
} else {
var event = document.createevent (' customevent ');
Event.initcustomevent (' My-event ', true, True, {some: ' data '});
}

El.dispatchevent (event);
Trigger Native

Jquery
$ (EL). Trigger (' change ');

Google Browser, Firefox browser, ie8+
if (document.createevent) {
var event = document.createevent (' htmlevents ');
Event.initevent (' Change ', true, false);
El.dispatchevent (event);
} else {
El.fireevent (' onchange ');
}
Google Browser, Firefox browser, ie9+
For a full list of event Types:https://developer.mozilla.org/en-us/docs/web/api/document.createevent
var event = document.createevent (' htmlevents ');
Event.initevent (' Change ', true, false);
El.dispatchevent (event);
Skills

Array each

Jquery
$.each (array, function (I, item) {

});

Google Browser, Firefox browser, ie8+
function ForEach (array, fn) {
for (i = 0; i < array.length; i++)
FN (Array[i], i);
}

ForEach (array, function (item, i) {

});

Google Browser, Firefox browser, ie9+
Array.foreach (function (item, i) {

});
Depth extension

Jquery
$.extend (True, {}, Obja, OBJB);
Google Browser, Firefox browser, ie8+
var deepextend = function (out) {
out = Out | | {};

for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];

if (!obj)
Continue

for (var key in obj) {
if (Obj.hasownproperty (key)) {
if (typeof obj[key] = = = ' object ')
Deepextend (Out[key], Obj[key]);
Else
Out[key] = Obj[key];
}
}
}

return out;
};

Deepextend ({}, Obja, OBJB);
Proxy

Jquery
$.proxy (FN, context);
Google Browser, Firefox browser, ie8+
Fn.apply (context, arguments);
Google Browser, Firefox browser, ie9+
Fn.bind (context);
Bind

Jquery
$.extend ({}, Obja, OBJB);
Google Browser, Firefox browser, ie8+
var extend = function (out) {
out = Out | | {};

for (var i = 1; i < arguments.length; i++) {
if (!arguments[i])
Continue

for (var key in Arguments[i]) {
if (Arguments[i].hasownproperty (key))
Out[key] = Arguments[i][key];
}
}

return out;
};

Extend ({}, Obja, OBJB);
Index of

Jquery
$.inarray (item, array);
Google Browser, Firefox browser, ie8+
function indexOf (array, item) {
for (var i = 0; i < Array.Length; i++) {
if (array[i] = = Item)
return i;
}
return-1;
}

IndexOf (array, item);
Google Browser, Firefox browser, ie9+
Array.indexof (item);
Is Array

Jquery
$.isarray (arr);

Google Browser, Firefox browser, ie8+
IsArray = Array.isarray | | Function (arr) {
return Object.prototype.toString.call (arr) = = ' [Object Array] ';
}

IsArray (arr);
Google Browser, Firefox browser, ie9+
Array.isarray (arr);
Map

Jquery
$.map (array, function (value, index) {

});

JS Google browser, Firefox browser, ie8+
function map (arr, fn) {
var results = [];
for (var i = 0; i < arr.length; i++)
Results.push (FN (arr[i], i));
return results;
}

Map (array, function (value, index) {

});
Google Browser, Firefox browser, ie9+
Array.map (function (value, index) {

});
Now

Jquery
$.now ();

Google Browser, Firefox browser, ie8+
New Date (). GetTime ();
Google Browser, Firefox browser, ie9+
Date.now ();
Parse Html

Jquery
$.parsehtml (htmlstring);

Google Browser, Firefox browser, ie8+
var parsehtml = function (str) {
var el = document.createelement (' div ');
el.innerhtml = str;
return el.children;
};

Parsehtml (htmlstring);
Google Browser, Firefox browser, ie9+
var parsehtml = function (str) {
var tmp = document.implementation.createHTMLDocument ();
Tmp.body.innerHTML = str;
return tmp.body.children;
};

Parsehtml (htmlstring);
Parsing Json

Jquery
$.parsejson (string);
Google Browser, Firefox browser, ie8+
Json.parse (string);
Trim

Jquery
$.trim (string);
Google Browser, Firefox browser, ie8+
String.Replace (/^\s+|\s+$/g, "");
Google Browser, Firefox browser, ie9+
String.Trim ();
Type

Jquery
$.type (obj);

Google Browser, Firefox browser, ie8+
Object.prototype.toString.call (obj)
. replace (/^\[object (. +) \]$/, "$")
. toLowerCase ();
Ajax

New Ajax Method Fetch ()

Basic FETCH usage

Let's use an example to compare the difference between using XMLHttpRequest and using the fetch. We want to request a URL to get the return result in JSON format.

The original XMLHttpRequest

A XMLHttpRequest request requires two listeners to capture the success and error two scenarios, and the open () and send () methods need to be invoked.

function Reqlistener () {
var data = Json.parse (This.responsetext);
Console.log (data);
}

function Reqerror (err) {
Console.log (' Fetch Error:-S ', err);
}

var oreq = new XMLHttpRequest ();
Oreq.onload = Reqlistener;
Oreq.onerror = Reqerror;
Oreq.open (' Get ', './api/some.json ', true);
Oreq.send ();
Fetch method:

The code for our fetch request is basically this:

Fetch ('./api/some.json ')
. Then (
Function (response) {
if (Response.Status!== 200) {
Console.log (' Looks like there is a problem. Status Code: ' +
Response.Status);
Return
}

Examine the text in the response
Response.json (). Then (function (data) {
Console.log (data);
});
}
)
. catch (function (err) {
Console.log (' Fetch Error:-S ', err);
});
Perform form data submission with fetch

In Web applications, submitting a form is a very common operation, and submitting form data with a fetch is also very concise.

The method and body parameter options are provided in the fetch.

Fetch (URL, {
Method: ' Post ',
Headers: {
"Content-type": "application/x-www-form-urlencoded;" Charset=utf-8 "
},
Body: ' Foo=bar&lorem=ipsum '
})
. Then (JSON)
. then (function (data) {
Console.log (' Request succeeded with JSON response ', data);
})
. catch (function (error) {
Console.log (' Request failed ', error);
});
Send user credential information in a FETCH request

If you want to include voucher information such as cookies in the fetch request, you can set the credentials parameter to the "include" value.

Fetch (URL, {
Credentials: ' Include '
})
Json

Jquery
$.getjson ('/my/url ', function (data) {

});

Google Browser, Firefox browser, ie8+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onreadystatechange = function () {
if (this.readystate = = 4) {
if (this.status >= && This.status < 400) {
success!
var data = Json.parse (This.responsetext);
} else {
Error:(
}
}
};

Request.send ();
request = NULL;

Google Browser, Firefox browser, ie9+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onload = function () {
if (request.status >= && Request.status < 400) {
success!
var data = Json.parse (Request.responsetext);
} else {
We reached our target server and but it returned an error

}
};

Request.onerror = function () {
There was a connection error of some sort
};

Request.send ();

Google Browser, Firefox browser, ie10+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onload = function () {
if (this.status >= && This.status < 400) {
success!
var data = Json.parse (This.response);
} else {
We reached our target server and but it returned an error

}
};

Request.onerror = function () {
There was a connection error of some sort
};

Request.send ();
Post

Jquery
$.ajax ({
Type: ' POST ',
URL: '/my/url ',
Data:data
});

Google Browser, Firefox browser, ie8+
var request = new XMLHttpRequest ();
Request.open (' POST ', '/my/url ', true);
Request.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded; Charset=utf-8 ');
Request.send (data);
Request

Jquery
$.ajax ({
Type: ' Get ',
URL: '/my/url ',
Success:function (RESP) {

},
Error:function () {

}
});

Google Browser, Firefox browser, ie8+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onreadystatechange = function () {
if (this.readystate = = 4) {
if (this.status >= && This.status < 400) {
success!
var resp = This.responsetext;
} else {
Error:(
}
}
};

Request.send ();
request = NULL;

Google Browser, Firefox browser, ie9+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onload = function () {
if (request.status >= && Request.status < 400) {
success!
var resp = Request.responsetext;
} else {
We reached our target server and but it returned an error

}
};

Request.onerror = function () {
There was a connection error of some sort
};

Request.send ();

Google Browser, Firefox browser, ie10+
var request = new XMLHttpRequest ();
Request.open (' Get ', '/my/url ', true);

Request.onload = function () {
if (this.status >= && This.status < 400) {
success!
var resp = this.response;
} else {
We reached our target server and but it returned an error

}
};

Request.onerror = function () {
There was a connection error of some sort
};

Request.send ();
Effects

Fade in

Jquery
$ (EL). FadeIn ();

Google Browser, Firefox browser, ie8+
function FadeIn (EL) {
var opacity = 0;

el.style.opacity = 0;
El.style.filter = ';

var last = +new Date ();
var tick = function () {
Opacity + = (new Date ()-last)/400;
El.style.opacity = opacity;
El.style.filter = ' alpha (opacity= ' + (opacity) | + ') ';

last = +new Date ();

if (Opacity < 1) {
(Window.requestanimationframe && requestanimationframe (tick)) | | settimeout (tick, 16);
}
};

Tick ();
}

FadeIn (EL);

Google Browser, Firefox browser, ie9+
function FadeIn (EL) {
el.style.opacity = 0;

var last = +new Date ();
var tick = function () {
El.style.opacity = +el.style.opacity + (new Date ()-last)/400;
last = +new Date ();

if (+el.style.opacity < 1) {
(Window.requestanimationframe && requestanimationframe (tick)) | | settimeout (tick, 16)
}
};

Tick ();
}

FadeIn (EL);

Google Browser, Firefox browser, ie10+
El.classList.add (' show ');
El.classList.remove (' hide ');
. Show {
Transition:opacity 400ms;
}
. Hide {
opacity:0;
}
Hide

Jquery
$ (EL). Hide ();

Google Browser, Firefox browser, ie8+
El.style.display = ' None ';
Show

Jquery
$ (EL). Show ();
Google Browser, Firefox browser, ie8+
El.style.display = ';

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.