Home > Software engineering >  sometimes I can access to id of my html tag sometimes not
sometimes I can access to id of my html tag sometimes not

Time:02-03

enter image description hereI want to get access to data-id linked to my icons to use them to manipulate the section related to these ids

but the problem is when I press the icons sometimes o get undefined sometimes its works I don't know why

please explain to me what I did wrong.


  <body >
    <header  id="home"></header>
    <main>
      <section  id="about"></section>
      <section  id="portfolio"></section>
      <section  id="contact"></section>
    </main>
    <div >
      <div  data-id="home">
        <i ></i>
      </div>
      <div  data-id="about">
        <i ></i>
      </div>
      <div  data-id="portfolio">
        <i ></i>
      </div>
      <div  data-id="contact">
        <i ></i>
      </div>
    </div>
  </body>
</html>

and this is the javascript

let active = document.querySelectorAll(".control");
let allsections = document.querySelectorAll(".main-content");
let section = document.querySelectorAll(".section");
function makingActive() {
  active.forEach((e) => {
    e.addEventListener("click", () => {
      let active_1 = document.querySelectorAll(".active-btn");
      active_1.forEach((e) => {
        e.classList.remove("active-btn");
      });
      e.classList.add("active-btn");
    });
  });
  allsections.forEach((e) => {
    e.addEventListener("click", (e) => {
      const id = e.target.dataset.id;
      console.log(id);
      section.forEach((sec) => {
        sec.classList.remove("active");
      });
      const secActive = document.getElementById(id);
      secActive.classList.add("active");
    });
  });
}

makingActive();

CodePudding user response:

I think you want something like this:

const allSections = Array.from(document.querySelectorAll('.section'))
const allControls = Array.from(document.querySelectorAll('.control'))

allSections.forEach((e) => {
  e.addEventListener('click', (e) => {
    const id = e.target.dataset.id
    const secActive = document.getElementById(id)
    
    console.clear()
    console.log('id:', id)
    
    allControls.forEach((sec) => {
      sec.classList.remove('active')
    })
    secActive.classList.add('active')
  })
})
.section {
  cursor: pointer;
}

.active {
  color: red;
}

.controls {
  margin: 20px 0 0;
  font-size: 20px;
}
<header  data-id="home">Home</header>
<main>
  <section  data-id="about">About</section>
  <section  data-id="portfolio">Portfolio</section>
  <section  data-id="contact">Contact</section>
</main>
<div >
  <div  id="home">
    <i ></i> -> home
  </div>
  <div  id="about">
    <i ></i> -> about
  </div>
  <div  id="portfolio">
    <i ></i> -> portfolio
  </div>
  <div  id="contact">
    <i ></i> -> contact
  </div>
</div>

  • Related