skip to Main Content

I want to have closing button in some sections in my web.
what js code do i need so that i can select all the divs with the class "close" and all of them do their jobs

i tried this but it only applies for the first element.
and when i change it to querySelectorAll i get the error that this is not a function.

let close = document.querySelector(".close");
close.addEventListener("click",function () {
    alert("msg");
})

2

Answers


  1. When you use querySelectorAll it returns an array of HTML elements, if you want to add a listener to all of them you could iterate over the array and add a listener to each element

    let closeItems = document.querySelectorAll(".close");
    
    closeItems.forEach(close=>{
      close.addEventListener("click",function () {
          alert("msg");
      })
    })
    
    Login or Signup to reply.
  2. You could set up a global action handler. Whenever you perform an action, get the action from the button and find its section.

    Now, you can toggle the state of the section, based on the action type.

    const messageCount = 15;
    for (let i = 0; i < messageCount; i++) {
      addSection({ title: `Section ${i}`, content: 'Hello World' });
    }
    
    // Globally listen to all action buttons
    document.addEventListener('click', function(event) {
      if (event.target.classList.contains('section-action')) {
        handleAction(event);
      }
    });
    
    function handleAction(event) {
      const section = event.target.closest('.section');
      const { action } = event.target.dataset;
      switch (action) {
        case 'collapse':
          const isExpanded = section.dataset.expanded === 'true';
          section.dataset.expanded = !isExpanded;
          break;
        case 'close':
          const isClosed = section.dataset.closed === 'true';
          section.dataset.closed = !isClosed;
          break;
        default:
          throw new Error(`unknown action: ${action}`)
      }
    }
    
    function addSection({ title, content }) {
      document.body.insertAdjacentHTML('beforeend', `
        <div class="section" data-closed="false" data-expanded="true">
          <div class="section-header">
            <div class="section-header-content">${title}</div>
            <div class="section-actions">
              <span class="section-action" data-action="collapse"></span>
              <span class="section-action" data-action="close"></span>
            </div>
          </div>
          <div class="section-content">${content}</div>
        </div>
      `);
    }
    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    body {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;
      gap: 0.25rem;
    }
    
    .section {
      display: flex;
      flex-direction: column;
      border: thin solid grey;
    }
    
    .section[data-closed="true"] {
      display: none;
    }
    
    .section[data-closed="false"] {
      display: flex;
    }
    
    .section[data-expanded="true"] .section-content {
      display: flex;
    }
    
    .section[data-expanded="false"] .section-content {
      display: none;
    }
    
    .section-header {
      display: flex;
      flex-direction: row;
      background: #eee;
      gap: 1rem;
      padding: 0.25rem;
      border-bottom: thin solid grey;
    }
    
    .section-header-content {
      flex: 1;
    }
    
    .section-actions {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.25rem;
    }
    
    .section-action {
      display: flex;
      align-items: center;
      justify-content: center;
      border: thin solid grey;
      width: 1rem;
      height: 1rem;
      background: grey;
      color: white;
      font-weight: bold;
      font-family: monospace;
    }
    
    .section-action:hover {
      cursor: pointer;
    }
    
    .section [data-action="close"] {
      background: red;
    }
    .section [data-action="close"]:after {
      content: "x";
    }
    
    .section [data-action="collapse"] {
      background: blue;
    }
    .section [data-action="collapse"]:after {
      content: ">";
    }
    .section[data-expanded="true"] [data-action="collapse"]:after {
      content: "v";
    }
    
    .section-content {
      padding: 0.25rem;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search