遍历HTML结构以搜索属性
Traversing an HTML structure searching for attribute
我有一个包含两个方法up()
和down()
的traverse
对象,这些方法的目标是在html中向上或向下循环,查找特定dataset-attribute
的第一个出现,如果找到,则返回该元素。
"特定"dataset-attribute
作为参数传递到方法中,例如我们有data-up
和data-down
。
var o1 = traverse.up(e.target,'up');
var o2 = traverse.down(e.target,'down');
现在,向上遍历方法traverse.up(e.target,'up')
工作得很好,因为parentNode与单击的元素(e.target)是一对一的关系。然而,我的问题是,当尝试向下遍历时,因为单击的元素可能有多个子元素,我需要循环遍历每个子元素及其子元素,等等…搜索dataset-down
属性。
问题:为什么我的traverse.down(e.target,'down')
方法不返回具有dataset-down
属性的HTML元素的第一个出现?
这是JSFiddle演示
//HTML
<body>
<div id='black'>
<div id='red' data-up='upwards'>
<div id='blue'>
<div id='green'>
<div id='yellow'></div>
<div id='royalblue' data-down='downwards'></div>
<div id='fuscia'></div>
</div>
</div>
</div>
</div>
</body>
//JS-
function init(){
document.getElementById('black').addEventListener('click', handles);
}
function handles(e){
// var o1 = traverse.up(e.target,'up');
var o2 = traverse.down(e.target,'down');
console.log(o2);
}
traverse={
up:function(o,a){
while(o.dataset[a] === undefined){
if(o.parentNode.tagName === 'HTML') break;
o = o.parentNode;
}
return o;
},
down:function(o,a){
if(o.dataset[a] === undefined){
if(o.children.length > 0){
o.children.forEach((o)=>{
traverse.down(o,a);
})
}
else console.log("DOES NOT HAVE CHILD");
}
else{
//console.log(o) **this does return the correct element with the data-down attribute however the return statement below isn't returning it back to the original caller.
return o;
}
}
};
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
document.onreadystatechange=()=>(document.readyState === 'interactive') ? init() : null;
类似这样的东西:
if(o.children.length > 0){
o.children.forEach((o)=>{
var t = traverse.down(o,a);
if (t) return t; // return the first element that matches. There might be more but we're ignoring them
});
// none were found
return false;
}
相关文章:
- 如何根据数值通过数据属性进行搜索并获得最接近的值
- 在JavaScript中编译搜索后,获取链接到函数的属性标记的Element
- 搜索具有特定属性集的非嵌套节点
- 在 XML 文件中搜索 TestComplete 中的特定属性值
- 使用 CSS3 数据属性进行客户端文本搜索
- 如何在 XML 中搜索特定属性以检索另一个属性
- 在 xml 中搜索属性
- Lodash搜索对象属性并修改值
- Lodash关于使用搜索词和多个属性名称进行筛选的帮助
- 如何在对象中搜索属性
- 遍历HTML结构以搜索属性
- 使用变量搜索窗口中的属性使用'在'中;
- Javascript Regex exec 在向搜索文本添加属性/引号后冻结
- 如何通过 jquery 通配符搜索数据属性的精确包含值
- 如何有效地搜索具有介于 jquery 之间的索引的 name 属性的输入
- 在属性名称中搜索带有冒号的 xpath 表达式会引发异常(节点.js元素树模块)
- 自动完成功能,用于按属性搜索 json 对象
- 具有近似值的搜索属性
- Lightswitch:具有字符串和整数搜索属性的参数(可能吗?)
- Jquery Token Input-传递属性动态搜索属性值