elements
Version:
prime dom library
104 lines (78 loc) • 2.65 kB
JavaScript
/*
traversal
*/"use strict"
var map = require("mout/array/map")
var slick = require("slick")
var $ = require("./base")
var gen = function(combinator, expression){
return map(slick.parse(expression || "*"), function(part){
return combinator + " " + part
}).join(", ")
}
var push_ = Array.prototype.push
$.implement({
search: function(expression){
if (this.length === 1) return $(slick.search(expression, this[0], new $))
var buffer = []
for (var i = 0, node; node = this[i]; i++) push_.apply(buffer, slick.search(expression, node))
buffer = $(buffer)
return buffer && buffer.sort()
},
find: function(expression){
if (this.length === 1) return $(slick.find(expression, this[0]))
for (var i = 0, node; node = this[i]; i++) {
var found = slick.find(expression, node)
if (found) return $(found)
}
return null
},
sort: function(){
return slick.sort(this)
},
matches: function(expression){
return slick.matches(this[0], expression)
},
contains: function(node){
return slick.contains(this[0], node)
},
nextSiblings: function(expression){
return this.search(gen('~', expression))
},
nextSibling: function(expression){
return this.find(gen('+', expression))
},
previousSiblings: function(expression){
return this.search(gen('!~', expression))
},
previousSibling: function(expression){
return this.find(gen('!+', expression))
},
children: function(expression){
return this.search(gen('>', expression))
},
firstChild: function(expression){
return this.find(gen('^', expression))
},
lastChild: function(expression){
return this.find(gen('!^', expression))
},
parent: function(expression){
var buffer = []
loop: for (var i = 0, node; node = this[i]; i++) while ((node = node.parentNode) && (node !== document)){
if (!expression || slick.matches(node, expression)){
buffer.push(node)
break loop
break
}
}
return $(buffer)
},
parents: function(expression){
var buffer = []
for (var i = 0, node; node = this[i]; i++) while ((node = node.parentNode) && (node !== document)){
if (!expression || slick.matches(node, expression)) buffer.push(node)
}
return $(buffer)
}
})
module.exports = $