I have two navigation and when i click on the menus, a border should be add to the parent. I did the navigation using ES6 class. I need only one object to make this functionality. Now it is working because i hardcoded the class name as follows e.target.closest(".one").style.border="2px solid green"; here i used .one instead of it, i need variable which needs to detect the closest class .one. Hopes my explanation make sense for everyone. If not, ask me i'll be eloborate more. Hopes anyone can help me. Following is my code. Thanks in Advance!
class Navigation{
constructor(parent) {
this.parent= document.querySelectorAll(parent);
}
addBorder(){
let li = this.parent.forEach((elem)=>{
elem.addEventListener("click",(e)=>{
e.target.closest(".one").style.border="2px solid green";
})
})
}
};
let one = new Navigation(".one");
one.addBorder();
nav {font-family:arial;width:15rem;}
nav ul {list-style:none;padding:0;margin:1rem;padding-left:.5rem;}
nav ul a {color:#777;text-decoration:none;padding:.5rem;}
<nav class="one">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<nav class="one">
<ul>
<li><a href="#">Services</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Support</a></li>
</ul>
</nav>
Is this along the lines of what you are trying to do? Added a new method to navigate up the DOM to find the parent as specified in the constructor. From that obtain it's class and proceed as you were....more or less
class Navigation {
constructor(parent) {
this.parent = document.querySelectorAll(parent);
};
find(e) {
let n = e.target;
while (n.tagName.toLowerCase() != this.parent.item(0).tagName.toLowerCase()) {
if (n.nodeName === 'BODY') return false;
n = n.parentNode;
}
return n;
};
addBorder() {
this.parent.forEach((elem) => {
elem.addEventListener("click", (e) => {
e.stopPropagation();
e.preventDefault();
let _cn = this.find(e).className;
e.target.closest(`.${_cn}`).classList.add('banana')
})
})
}
};
let one = new Navigation("nav");
one.addBorder();
nav {
font-family: arial;
width: 15rem;
}
nav ul {
list-style: none;
padding: 0;
margin: 1rem;
padding-left: .5rem;
}
nav ul a {
color: #777;
text-decoration: none;
padding: 0.5rem;
}
/* only to aid visualisation */
.banana {
border: 5px solid green;
background: white;
box-shadow: 0 0 2rem yellow;
}
<nav class="one" id='a'>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<nav class="one" id='b'>
<ul>
<li><a href="#">Services</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Support</a></li>
</ul>
</nav>