查找元素
元素节点的查找
通过节点属性查找
通过节点的相关属性可以直接取得对象节点的父子兄弟节点。
| 属性 | 说明 |
|---|---|
| childNodes | 获取当前元素节点的所有子节点 |
| firstChild | 获取当前元素节点的第一个子节点 |
| lastChild | 获取当前元素节点的最后一个子节点 |
| ownerDocument | 获取该节点的文档根节点,相当与document |
| parentNode | 获取当前节点的父节点 |
| previousSibling | 获取当前节点的前一个同级节点 |
| nextSibling | 获取当前节点的后一个同级节点 |
通过以上属性取得的子节点和兄弟节点,不仅有元素节点,也有文本节点等其他类型的节点,根据需要可以通过node.nodeType属性进行判断。
通过ID查找
节点的ID在DOM文档中具有唯一性,如果知道查找对象节点的ID,这种方法将是查询性能最高的方法。 domlib的find()方法可以通过ID查询节点,下面的代码将会返回contextNode节点(可以是document)的子孙节点中ID为“id1”的节点。
var node = domlib.find(contextNode,"#id1");
find()方法内部调用DOM API的contextNode.getElementById()方法。
通过类名查找
domlib的find()方法也可以通过类名查询节点,下面的代码将会返回contextNode节点(可以是document)的子孙节点中类名为”cls1”的节点。
var node = domlib.find(contextNode,".cls");
find()方法内部调用DOM API的contextNode.getElementsByClassName()方法。
通过选择符查找
domlib的find()方法也可以通过指定更复杂的选择符来查询节点,选择符的语法遵从CSS3规范。 下面的代码将会返回contextNode节点(可以是document)的container节点(类名位container的DIV元素)的<a>子元素。
var node = domlib.find(contextNode,"div.container > a");
find()方法内部调用DOM API的contextNode.querySelectorAll()或contextNode.querySelector()方法。
工具函数列表
uDOMlib所提供的工具函数之中,有一部分与查找元素相关,下面列出部分函数的源代码实现以供参考。
children
children: function(node,selector) {
var childNodes = node.childNodes,
result = [];
for (var i=0;i<childNodes.length;i++){
if (this.matchs(childNodes[i],selector)) {
result.push(childNodes[i]);
}
}
return result;
}
closest
closest: function(node,selector,checkSelf) {
node = checkSelf ? node : node.parentNode;
while (node && !(this.matches(node, selector))){
node = node.parentNode;
}
return node;
}
find
查找元素列表
find: function(node,selector,single) {
var matched,ret;
if (matched = selector.match(simpleIdSelectorRE)) {
// ID
return node.getElementById(matched[1]);
}
if (matched = selector.match(simpleClassSelectorRE)) {
// Class
var ret = node.getElementsByClassName(matched[1]);
if (single && ret){
ret = ret[0];
}
return ret;
}
// Selector
if (single) {
return node.querySelector(selector)
} else {
return node.querySelectorAll(selector)
}
}
findSingle
matches
matches: function(node,selector) {
if (!selector || !node || node.nodeType !== 1) {
return false
}
var matchesSelector = node.webkitMatchesSelector ||
node.mozMatchesSelector ||
node.oMatchesSelector ||
node.matchesSelector;
return matchesSelector.call(node, selector)
}
parents
parents: function(node,selector) {
var ancestors = [];
while (node = node.parentNode) {
if (this.matches(node, selector)){
ancestors.push(node);
}
}
return ancestors;
}