jQuery的原生替代,参考自你不需要jQuery,对其进行了更清晰的总结与分类,现代游览器基本都支持(ie10+以上),只整理了最简洁实用的原生代码,过分累赘的实现没有加入
元素获取
$(selector) |
document.querySelectorAll(selector) |
$(el).find(selector) |
el.querySelectorAll(selector) |
$(el).prev() |
el.previousElementSibling |
$(el).next() |
el.nextElementSibling |
$(el).first() |
el.firstElementChild |
$(el).last() |
el.lastElementChild |
$(el).parent() |
el.parentNode |
$(el).offsetParent() |
el.offsetParent |
$(el).children() |
el.children |
$(el).siblings() |
Array.prototype.filter.call(el.parentNode.children, child => child !== el) |
dom操作
$(el).before(htmlString) |
el.insertAdjacentHTML('beforebegin', htmlString) => el.before(string) |
$(el).after(htmlString) |
el.insertAdjacentHTML('afterend', htmlString) => el.after(string) |
$(parent).prepend(el) |
parent.insertBefore(el, parent.firstChild) => el.prepend(htmlString) |
$(parent).append(el) |
parent.appendChild(el) => el.append(htmlString) |
$(el).remove() |
el.parentNode.removeChild(el) => el.remove() |
$(el).clone() |
el.cloneNode(true) |
$(el).empty() |
el.innerHTML = '' |
$(el).replaceWith(string) |
el.outerHTML = string |
$(el).html(string) |
el.innerHTML = string |
$(el).text(string) |
el.textContent = string |
$(el).val(string) |
el.value = string |
$(el).html() |
el.innerHTML |
$(el).text() |
el.textContent |
$(el).val() |
el.value |
样式操作
$(el).hasClass(className) |
el.classList.contains(className) |
$(el).addClass(className) |
el.classList.add(className) |
$(el).removeClass(className) |
el.classList.remove(className) |
$(el).toggleClass(className) |
el.classList.toggle(className) |
$(el).css(ruleName) |
getComputedStyle(el)[ruleName] |
$(el).css('width', '20px') |
el.style.width = '20px' |
属性操作
$(el).attr('title') |
el.getAttribute('title') |
$(el).attr('title', string) |
el.setAttribute('title', string) |
位置/尺寸
$(el).position() |
{ left: el.offsetLeft, top: el.offsetTop } |
$(el).offset() |
el.getBoundingClientRect() |
$(el).outerWidth() |
el.offsetWidth |
$(el).outerHeight() |
el.offsetHeight |
$(el).scrollTop() |
el.scrollTop |
$(el).scrollLeft() |
el.scrollLeft |
特效
$(el).hide() |
el.style.display = 'none' |
$(el).show() |
el.style.display = '' |
dom载入完毕
$(方法) |
document.addEventListener('DOMContentLoaded', 方法) |