前端发展很快,现代浏览器原生API已经足够好用。我们并不需要为了操作DOM、Event等再学习Jquery的API。同时由于React、Angular、Vue等框架的流行,直接操作DOM不再是好的模式,jQuery使用场景大大减少。本项目总结了大部分jQuery API替代的方法,暂时只支持IE10+以上的浏览器。
1. Query Selector
常用的class、ID、属性选择器都可以使用document.querySelector
或者 document.querySelecorAll
替代。区别是:
-
document.querySelector
返回第一个匹配的Element -
document.querySelectorAll
返回所有匹配的Element组成的NodeList。它可以通过[].slice.call()
把它转成Array - 如果匹配不到任何Element,jQuery返回空数组
[]
,但document.querySelectorAll
返回null
,注意空指针异常。当找不到时,也可以试用||
设置默认值,如document.querySelectotAll(selector)||[]
注意:
document.querySelector
和document.querySelectorAll
性能很差,尽量使用document.getElementById
、document.getElementsByClassName
或者document.getElementsByTagName
。
- 1.0. Query by
selector
//jQuery
$('selector')
//Native
document.querySelectorAll('selector');
- 1.1 Qeury by
class
//jQuery
$('.css')
//Native
document.getElementsByClassName('selector');
- 1.2 Qeury by
id
//jQuery
$('#id')
//Native
document.getElementById('id');
-
1.3 Query by
attribute
// jQuery $('a[target=_blank]'); //Native document.querySelector('a[target= _blank]');
-
1.4 Find sth
- Find nodes
```javascript
//jQuery
$el.find('li');//Native el.querySelector('li') ```
- Find body
//jQuery
$('body');
//Native
document.body;
```
- Find Attribute
//jQuery
$el.attr('foo');
//Native
e.getAttribute('foo');
```
- 1.5 Sibling/Previous/Next Elements
-
Sibling elements
//jQuery $el.sibglings(); //Navtive [].filter.call(el.parentNode.children,function(child){ return child!==el; });
-
Previous elements
//jQuery $el.prev(); //Navtive el.previousElementSibling;
-
Next elements
//jQuery $el.next(); //Navtive el.nextElementSibling;
- 1.6 Closest
Closest获得匹配选择器的第一个祖先元素,从当前元素开始沿DOM树向上。//jQuery $el.closest(queryString); //Navtive
function closest(el, selector) {
const machesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el)
if (matchesSelector.call(el, selector)) {
return el;
} else {
el = el.parentElement;
}
}
return null;
```
- 1.7 Parents Until
获取当前每一个元素匹配元素集的祖先,不包括元素本身
//jQuery
$el.parentsUntil(selector,filter);
//Native
function parentUntil(el, selector, filter) {
const result = [];
const matchesSelector = el.matchesSelector || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
//match start from parent
el = el.parentElement;
while (el && !matchesSelector.call(el, selector)) {
if (!filter) {
result.push(el);
} else {
if (matchesSelector.call(el, filter)) {
result.push(el);
}
}
el = el.parentElement;
}
return result;
}
-
1.8 Form
- Input/Textarea
//jQuery $('#my-input').val(); //Native document.querySelector('#my-input').value;
-
Get index of e.currentTarget between
.radio
//jQuery $(e.currentTarget).index('.radio'); //Native [].indexOf.call(document.querySelectorAll('.radio'),e.currentTarget);
-
1.9 Iframe Contents
jQuery 对象的iframecontents
返回的是iframe内的document- Iframe contents
//jQuery $iframe.contents(); //Native iframe.contentDocument;
2. CSS & Style
- 2.1 CSS
- Get Style