Skip to content
Advertisement

how to add and remove text with javascript on a multi-p

i tried to add and remove the text of a box clicking on a different series of p this is the code. click1 is associated by text1 and same click2 text2 ecc. the goal i want to achieve is click on click1 and the only text that appears is text1 same thing for click2 text2 ecc.

let container = document.querySelector(".container");
container.addEventListener("click", ({
  target
}) => {
  if (target.nodeName !== "P") return; // return if p is not clicked
  Array.from(document.querySelectorAll(".container1>p")).forEach(p => p.classList.remove("active1")); // make the others inactive
  target.classList.toggle("active1");
})
   .container1 p {
     display: none;
    }
    
    .container1 p.active1 {
      display:initial;
    }
 <div class="container">
            <p class="active">click1</p>
            <p>click2</p>
            <p>click3 </p>
            <p>click4</p>
            <p>click5</p>
        </div>
        <div class="container1">
            <p class="active1">
              text1
            </p>
            <p>
              text 2             
            </p>
              <p>
              text 3            
            </p> 
            <p>
              text 4             
            </p>
         </div>

Advertisement

Answer

let container = document.querySelector(".container");
let p_in_container = document.querySelectorAll(".container>p");
let p_in_container1 = document.querySelectorAll(".container1>p");

container.addEventListener("click", ({target}) => {
  if (target.nodeName !== "P") return; // return if p is not clicked

  var idx_clicked = Array.from(p_in_container).indexOf(target);
  var target_p = p_in_container1[idx_clicked];
  // var is_active = target_p.classList.contains('active1');

  Array.from(p_in_container1).forEach(p => p.classList.remove("active1")); // make the others inactive
  // p_in_container1[idx_clicked].classList.toggle("active1", !is_active);
  p_in_container1[idx_clicked].classList.toggle("active1");
  ;
})
   .container1 p {
     display: none;
    }
    
    .container1 p.active1 {
      display:initial;
    }
 <div class="container">
     <p class="active">click1</p>
     <p>click2</p>
     <p>click3 </p>
     <p>click4</p>
     <p>click5</p>
 </div>
 <div class="container1">
     <p class="active1">
         text1
     </p>
     <p>
         text 2             
     </p>
     <p>
         text 3            
     </p> 
     <p>
         text 4             
     </p>
     <p>
         text 5             
     </p>
 </div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement