首页 > 建站教程 > JS、jQ、TS >  用纯JavaScript替代jQuery之元素操作篇正文

用纯JavaScript替代jQuery之元素操作篇

jQuery是非常优秀的工具,它能让我们开发项目时变得更容易。

但如果你想从零开始开发一个全新的项目,你应该考虑一下你的项目是否真的需要引入jQuery。也许你只需要几行技巧性的代码就能解决问题。如果你的项目是面向最新的现代浏览器,你真的可以考虑其它的一些简单的技术来代替jQuery。
浏览器的进步给我们带来了很多先进的JavaScript特征,新出现的原生内置(native)JavaScript功能可以很大程度的实现jQuery提供的功能。如果你能了解这些JavaScript新技术,就能在很多地方用纯JavaScript实现以前需要jQuery才能实现的技术。

>>>>Add Class

jQuery
$(el).addClass(className);
谷歌浏览器,火狐浏览器,IE8+
if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;
谷歌浏览器,火狐浏览器,IE10+
el.classList.add(className);
>>>>After

jQuery
$(el).after(htmlString);
谷歌浏览器,火狐浏览器,IE8+
el.insertAdjacentHTML('afterend', htmlString);
>>>>Append

jQuery
$(parent).append(el);
谷歌浏览器,火狐浏览器,IE8+
parent.appendChild(el);
>>>>Before

jQuery
$(el).before(htmlString);
谷歌浏览器,火狐浏览器,IE8+
el.insertAdjacentHTML('beforebegin', htmlString);
>>>>Children

jQuery
$(el).children();
谷歌浏览器,火狐浏览器,IE8+
var children = [];
for (var i = el.children.length; i--;) {
  //跳过注释标签 IE8
  if (el.children[i].nodeType != 8)
    children.unshift(el.children[i]);
}
谷歌浏览器,火狐浏览器,IE9+
el.children
>>>>Clone

jQuery
$(el).clone();
谷歌浏览器,火狐浏览器,IE8+
el.cloneNode(true);
>>>>Contains

jQuery
$.contains(el, child);
谷歌浏览器,火狐浏览器,IE8+
el !== child && el.contains(child);
>>>>Contains Selector

jQuery
$(el).find(selector).length;
谷歌浏览器,火狐浏览器,IE8+
el.querySelector(selector) !== null
>>>>Each

jQuery
$(selector).each(function(i, el){
});
谷歌浏览器,火狐浏览器,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){
});
谷歌浏览器,火狐浏览器,IE9+
var elements = document.querySelectorAll(selector);
Array.prototype.forEach.call(elements, function(el, i){
});
>>>>Empty

jQuery
$(el).empty();
谷歌浏览器,火狐浏览器,IE8+
while(el.firstChild)
  el.removeChild(el.firstChild);
谷歌浏览器,火狐浏览器,IE9+
el.innerHTML = '';
>>>>过滤

jQuery
$(selector).filter(filterFn);
谷歌浏览器,火狐浏览器,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);
谷歌浏览器,火狐浏览器,IE9+
Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
>>>>查找子元素

jQuery
$(el).find(selector);
谷歌浏览器,火狐浏览器,IE8+
el.querySelectorAll(selector);
>>>>查找

jQuery
$('.my #awesome selector');
谷歌浏览器,火狐浏览器,IE8+
document.querySelectorAll('.my #awesome selector');
>>>>获取属性值

jQuery
$(el).attr('tabindex');
谷歌浏览器,火狐浏览器,IE8+
el.getAttribute('tabindex');
>>>>获取Html内容

jQuery
$(el).html();
谷歌浏览器,火狐浏览器,IE8+
el.innerHTML
>>>>获取外层Html内容

jQuery
$('<div>').append($(el).clone()).html();
谷歌浏览器,火狐浏览器,IE8+
el.outerHTML
>>>>获取CSS样式

jQuery
$(el).css(ruleName);
谷歌浏览器,火狐浏览器,IE8+
// Varies based on the properties being retrieved, some can be retrieved from el.currentStyle
// https://github.com/jonathantneal/Polyfills-for-IE8/blob/master/getComputedStyle.js
谷歌浏览器,火狐浏览器,IE9+
getComputedStyle(el)[ruleName];
>>>>获取文本内容

jQuery
$(el).text();
谷歌浏览器,火狐浏览器,IE8+
el.textContent || el.innerText
谷歌浏览器,火狐浏览器,IE9+
el.textContent
>>>>Has Class

jQuery
$(el).hasClass(className);
谷歌浏览器,火狐浏览器,IE8+
if (el.classList)
  el.classList.contains(className);
else
  new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
谷歌浏览器,火狐浏览器,IE10+
el.classList.contains(className);
>>>>元素比较

jQuery
$(el).is($(otherEl));
谷歌浏览器,火狐浏览器,IE8+
el === otherEl
>>>>比较类名

jQuery
$(el).is('.my-class');
谷歌浏览器,火狐浏览器,IE8+
var matches = function(el, selector) {
  var _matches = (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || 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');
谷歌浏览器,火狐浏览器,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();
谷歌浏览器,火狐浏览器,IE8+
// nextSibling可能包含文本节点,要过滤
function nextElementSibling(el) {
  do { el = el.nextSibling; } while ( el && el.nodeType !== 1 );
  return el;
}

el.nextElementSibling || nextElementSibling(el);
谷歌浏览器,火狐浏览器,IE9+
el.nextElementSibling
>>>>Offset

jQuery
$(el).offset();
谷歌浏览器,火狐浏览器,IE8+
var rect = el.getBoundingClientRect()

{
  top: rect.top + document.body.scrollTop,
  left: rect.left + document.body.scrollLeft
}
>>>>Offset Parent

jQuery
$(el).offsetParent();
谷歌浏览器,火狐浏览器,IE8+
el.offsetParent || el
>>>>高+padding+border获取

jQuery
$(el).outerHeight();
谷歌浏览器,火狐浏览器,IE8+
el.offsetHeight
>>>>高+padding+border+margin获取

jQuery
$(el).outerHeight(true);
谷歌浏览器,火狐浏览器,IE8+
function outerHeight(el) {
  var height = el.offsetHeight;
  var style = el.currentStyle || getComputedStyle(el);

  height += parseInt(style.marginTop) + parseInt(style.marginBottom);
  return height;
}

outerHeight(el);
谷歌浏览器,火狐浏览器,IE9+
function outerHeight(el) {
  var height = el.offsetHeight;
  var style = getComputedStyle(el);

  height += parseInt(style.marginTop) + parseInt(style.marginBottom);
  return height;
}

outerHeight(el);
>>>>宽+padding+border获取

jQuery
$(el).outerWidth();
谷歌浏览器,火狐浏览器,IE8+
el.offsetWidth
>>>>Parent

jQuery
$(el).parent();
谷歌浏览器,火狐浏览器,IE8+
el.parentNode
>>>>宽+padding+border+margin获取

jQuery
$(el).outerWidth(true);
谷歌浏览器,火狐浏览器,IE8+
function outerWidth(el) {
  var width = el.offsetWidth;
  var style = el.currentStyle || getComputedStyle(el);

  width += parseInt(style.marginLeft) + parseInt(style.marginRight);
  return width;
}

outerWidth(el);
谷歌浏览器,火狐浏览器,IE9+
function outerWidth(el) {
  var width = el.offsetWidth;
  var style = getComputedStyle(el);

  width += parseInt(style.marginLeft) + parseInt(style.marginRight);
  return width;
}

outerWidth(el);
>>>>Position

jQuery
$(el).position();
谷歌浏览器,火狐浏览器,IE8+
{left: el.offsetLeft, top: el.offsetTop}

Position Relative To Viewport
jQuery

var offset = el.offset();

{
  top: offset.top - document.body.scrollTop,
  left: offset.left - document.body.scrollLeft
}
谷歌浏览器,火狐浏览器,IE8+
el.getBoundingClientRect()
>>>>Prepend

jQuery
$(parent).prepend(el);
谷歌浏览器,火狐浏览器,IE8+
parent.insertBefore(el, parent.firstChild);
>>>>Prev

jQuery
$(el).prev();
谷歌浏览器,火狐浏览器,IE8+
// prevSibling 包含文本节点
function previousElementSibling(el) {
  do { el = el.previousSibling; } while ( el && el.nodeType !== 1 );
  return el;
}

el.previousElementSibling || previousElementSibling(el);
谷歌浏览器,火狐浏览器,IE9+
el.previousElementSibling
>>>>删除节点remove

jQuery
$(el).remove();
谷歌浏览器,火狐浏览器,IE8+
el.parentNode.removeChild(el);
>>>>删除class

jQuery
$(el).removeClass(className);
谷歌浏览器,火狐浏览器,IE8+
if (el.classList)
  el.classList.remove(className);
else
  el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
谷歌浏览器,火狐浏览器,IE10+
el.classList.remove(className);
>>>>替换replaceWidth

jQuery
$(el).replaceWith(string);
谷歌浏览器,火狐浏览器,IE8+
el.outerHTML = string;
>>>>Set Attributes

jQuery
$(el).attr('tabindex', 3);
谷歌浏览器,火狐浏览器,IE8+
el.setAttribute('tabindex', 3);
>>>>设置容器里面的html

jQuery
$(el).html(string);
谷歌浏览器,火狐浏览器,IE8+
el.innerHTML = string;
>>>>Set Style

jQuery
$(el).css('border-width', '20px');
谷歌浏览器,火狐浏览器,IE8+
// Use a class if possible
el.style.borderWidth = '20px';
>>>>设置容器里面的text文本

jQuery
$(el).text(string);
谷歌浏览器,火狐浏览器,IE8+
if (el.textContent !== undefined)
  el.textContent = string;
else
  el.innerText = string;
谷歌浏览器,火狐浏览器,IE9+
el.textContent = string;
>>>>选择所有兄弟节点

jQuery
$(el).siblings();
谷歌浏览器,火狐浏览器,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;
  }
}
谷歌浏览器,火狐浏览器,IE9+
Array.prototype.filter.call(el.parentNode.children, function(child){
  return child !== el;
});
>>>>切换样式toggleClass

jQuery
$(el).toggleClass(className);
谷歌浏览器,火狐浏览器,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(' ');
}
谷歌浏览器,火狐浏览器,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(' ');
}
谷歌浏览器,火狐浏览器,IE10+
el.classList.toggle(className);