Native JavaScript Equivalents of jQuery Methods: the DOM and Forms
等同于JQuery方法的原生JavaScript:Dom和表單
DOM 選擇器
JQuery訪問DOM節(jié)點(diǎn)使用CSS選擇器語法县耽,例如
// ID為first的文章里所有summary類的段落
var n = $("article#first p.summary");
等價的原生js
var n = document.querySelectorAll("article#first p.summary");
document.querySelectorAll
在所有的現(xiàn)代瀏覽器及IE8中都實(shí)現(xiàn)了苍姜,但是jQuery支持許多額外的高級選擇器王暗,大多數(shù)情況下凰盔,在$()
的包裝下運(yùn)行的是document.querySelectorAll
原生JavaScript也提供了四種替代方法它們比querySelectorAll查詢速度更快裹芝,前提是你的項(xiàng)目能夠使用它們
- document.querySelector(selector) --僅取得地一個匹配到的節(jié)點(diǎn)
- document.getElementById(idname) --取得一個節(jié)點(diǎn)通過它的ID
- document.getElementsByTagName(tagname) --取得匹配一個元素節(jié)點(diǎn)的節(jié)點(diǎn)列表
- document.getElementsByClassName(class) --取得一個確切的類名的節(jié)點(diǎn)列表
getElementsByTagName和getElementsByClassName方法也能夠被用在某一個節(jié)點(diǎn)列表上坝橡,這樣可以限制特定的祖先元素,例如
var n = document.getElementById("first");
var p = n.getElementsByTagName("p");
作者做了一項(xiàng)測試蝗羊,使用jQuery2.0和原生的JavaScript獲取一個頁面上的同一個元素節(jié)點(diǎn),往往原生的速度要快仁锯,也證明了通過id或是class獲得節(jié)點(diǎn)要比querySelectorAll要快
DOM操作
jQuery提供了許多方法向DOM添加內(nèi)容耀找,例如
$("#container").append("<p>more content</p>");
它的原理是使用了原生的innerHTML方法,例如
document.getElementById("container").innerHTML += "<p>more content</p>";
你也可是使用DOM創(chuàng)建技術(shù)业崖,他們更安全但是不比innerHTML快
var p = document.createElement("p");
p.appendChild(document.createTextNode("more content");
document.getElementById("container").appendChild(p);
我們也能通過jQuery移除所有的子節(jié)點(diǎn):
$("#container").empty();
等價的原生js使用innerHTM:
document.getElementById("container").innerHTML = null;
或者一個小函數(shù)
var c = document.getElementById("container");
while (c.lastChild) c.removeChild(c.lastChild);
最后野芒,我們使用jQuery從DOM移除這整個元素:
$("#container").remove();
或者原生js
var c = document.getElementById("container");
c.parentNode.removeChild(c);
SVG
SVG也有DOM,但是jQuery沒有向這些對象提供一個直接的操作方法双炕,因?yàn)橥ǔP枰褂孟馽reateElementNS和getAttributeNS.但是有許多插件可供使用狞悲,但是更有效的方法是自己打代碼或者使用像Rapha?l和svg.js這樣的庫
HTML5表單
使用jQuery或是原生js?
都不要
HTML5指出不同的input type妇斤,例如 emails, telephones, URLs, numbers, times, dates, colors和通過正則表達(dá)式的自定義表單摇锋,例如,如果你想要強(qiáng)制用戶輸入郵箱地址站超,可以使用:
<input type="email" name="email" required="required" />