I have a traverse
object containing two methods up()
and down()
, the goals of these methods are to loop upward or downward through the html looking for the first occurrence of specific dataset-attribute
and if found return that element.
The "specific" dataset-attribute
is passed as a param into the methods, for example purposes we have data-up
and data-down
.
var o1 = traverse.up(e.target,'up');
var o2 = traverse.down(e.target,'down');
Now the traversing up method traverse.up(e.target,'up')
works fine since the parentNode is a one-to-one relation to the element clicked (e.target) however my problem is when trying to traverse downwards since the element clicked (e.target) may have multiple children, I would need to loop through each child and it's children, etc... searching for the dataset-down
attribute.
Question: Why isn't my traverse.down(e.target,'down')
method return the first occurrence of an HTML element with the dataset-down
attribute?
Here is the JSFiddle demo
//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;