Wednesday, 18 May 2022

How to take off class when click on another element and show relative content

I got the following code, but when I click the menu, it uses .active class but when I click another element it doesn't remove the class but adds the clicked item e.g. If I have more menu and content I have to do a lot if else

How can I use active class on the element that had been clicked and show its content only?

const app = document.querySelector("#app");

/**
 *1. create div
 * attach a class to it
 * add menu items to it
 * attach item to div 1
 * attach div to app
 * show each div content when that div is clicked e.g. when description is clicked, it show description div
 * When clicked it showed shows its content and hides other
 */
const div = document.createElement("div");
div.className = "navigation";
const ul = document.createElement("ul");
const li = document.createElement("li");;
// const items = ["Description", "Delivery","Delivery"];
// items.forEach((item)=>{
//   li.textContent += item
//   ul.appendChild(li);
// })
ul.innerHTML = `
 <li><a href="#">Description</a></li>
 <li><a href="#">Delivery</a></li>
 <li><a href="#">Returns</a></li>
`
div.appendChild(ul);
app.insertAdjacentElement("afterbegin",div);

const contentDiv = document.createElement("div");
contentDiv.className = "contentDescription";
contentDiv.innerHTML = `
<h2>Description</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus facere enim repudiandae iusto unde 
    quam a sapiente libero ullam consequuntur!</p>
`
div.insertAdjacentElement("beforeend", contentDiv)
const nodeToArray = document.querySelectorAll("li");

nodeToArray.forEach((arr)=>{
    arr.addEventListener("click", (e)=>{
       if(e.target.innerText == 'Description'){
            e.target.className ="active"
       }else if(e.target.innerText == 'Delivery'){
           e.target.className = "active";
           document.querySelector(".contentDescription").style.display = "none"
       }
    })
})
li{
    list-style: none;
}
ul{
    display: grid;
    width: 100%;
    grid-template-columns: repeat(3, auto);
    justify-content: space-evenly;
}
a{
    text-decoration: none;
    color: black;
}
.active{
   border-bottom:2px solid black;
}
    <div id="app">
    </div>


from How to take off class when click on another element and show relative content

No comments:

Post a Comment