vue2/src/util/dom.js

136 lines
2.2 KiB
JavaScript
Raw Normal View History

2014-08-12 20:59:49 +08:00
var config = require('../config')
2014-08-23 06:27:06 +08:00
/**
* Check if a node is in the document.
*
* @param {Node} node
* @return {Boolean}
*/
var doc =
typeof document !== 'undefined' &&
document.documentElement
exports.inDoc = function (node) {
return doc && doc.contains(node)
}
2014-08-12 20:59:49 +08:00
/**
* Extract an attribute from a node.
*
* @param {Node} node
* @param {String} attr
*/
exports.attr = function (node, attr) {
2014-08-13 08:09:37 +08:00
attr = config.prefix + attr
2014-08-12 20:59:49 +08:00
var val = node.getAttribute(attr)
2014-08-13 13:30:33 +08:00
if (val !== null) {
node.removeAttribute(attr)
}
2014-08-12 20:59:49 +08:00
return val
}
2014-07-27 03:56:32 +08:00
/**
* Insert el before target
*
* @param {Element} el
* @param {Element} target
*/
exports.before = function (el, target) {
target.parentNode.insertBefore(el, target)
}
/**
* Insert el after target
*
* @param {Element} el
* @param {Element} target
*/
exports.after = function (el, target) {
if (target.nextSibling) {
exports.before(el, target.nextSibling)
} else {
target.parentNode.appendChild(el)
}
}
/**
* Remove el from DOM
*
* @param {Element} el
*/
exports.remove = function (el) {
el.parentNode.removeChild(el)
}
/**
* Prepend el to target
*
* @param {Element} el
* @param {Element} target
*/
exports.prepend = function (el, target) {
if (target.firstChild) {
exports.before(el, target.firstChild)
} else {
target.appendChild(el)
}
}
2014-08-21 06:46:42 +08:00
/**
* Replace target with el
*
* @param {Element} target
* @param {Element} el
*/
exports.replace = function (target, el) {
var parent = target.parentNode
2014-09-05 22:19:43 +08:00
parent.replaceChild(el, target)
2014-08-21 06:46:42 +08:00
}
2014-07-27 03:56:32 +08:00
/**
* Copy attributes from one element to another.
*
* @param {Element} from
* @param {Element} to
*/
exports.copyAttributes = function (from, to) {
if (from.hasAttributes()) {
var attrs = from.attributes
for (var i = 0, l = attrs.length; i < l; i++) {
var attr = attrs[i]
to.setAttribute(attr.name, attr.value)
}
}
2014-08-31 11:08:00 +08:00
}
/**
* Add event listener shorthand.
*
* @param {Element} el
* @param {String} event
* @param {Function} cb
*/
exports.on = function (el, event, cb) {
el.addEventListener(event, cb)
}
/**
* Remove event listener shorthand.
*
* @param {Element} el
* @param {String} event
* @param {Function} cb
*/
exports.off = function (el, event, cb) {
el.removeEventListener(event, cb)
2014-07-27 03:56:32 +08:00
}