Home > Enterprise >  How to click one id from a list of ids?
How to click one id from a list of ids?

Time:06-22

I have a list of ids, when one of them is clicked I want to give it the attribute .className="open. So far what I've done is to put all ids in a list and try to loop through them.

      const memberB = document.querySelectorAll('#memberA, #memberAA, #memberAAA ');
  for (var i = 0; i < memberB.length; i  ) {
    memberB[i].onclick = function(){
        alert(memberB[i])
        if(memberB[i].className=="open"){
            memberB[i].className="";
        }
        else{
            memberB[i].className="open";
        }
  }

What did I do wrong, I try to alert to see if I get the element that i clicked, all i get is 'undefined'.

CodePudding user response:

you can use forEach to loop the NodeList which use querySelectorAll method, and use addEventListener to watch click event happen on all the elements you selected. Finally, use Element.classList.toggle method to toggle the class open or close

there is an example of toggle its background color after click

const members = document.querySelectorAll('.member');
members.forEach(member => {
  member.addEventListener('click', e => {
    e.target.classList.toggle('hight-light');
  });
});
.member {
  background-color: gray;
}

.hight-light {
  background-color: green;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
</div>

CodePudding user response:

I have a code snippet I like to keep around to do these kind of things in a single event listener

window.addEvent = (event_type, target, callback) => {
  document.addEventListener(event_type, function (event) {
    // If the event doesn't have a target
    // Or the target doesn't look like a DOM element (no matches method
    // Bail from the listener
    if (event.target && typeof (event.target.matches) === 'function') {
      if (!event.target.matches(target)) {
        // If the element triggering the event is contained in the selector
        // Copy the event and trigger it on the right target (keep original in case)
        if (event.target.closest(target)) {
          const new_event = new CustomEvent(event.type, event);
          new_event.data = { originalTarget: event.target };
          event.target.closest(target).dispatchEvent(new_event);
        }
      } else {
        callback(event);
      }
    }
  });
};

then in your case I'd do this

window.addEvent('click', '#memberA,#memberAA,#memberAAA', (event) => {
 event.target.classList.toggle('open');
});

CodePudding user response:

The script runs befor the DOM elements load.

You can put the script as a function inside an $(document).ready such that it runs after all the elements have been loaded.

$(document).ready(
        function () {
            const memberB = document.querySelectorAll('#memberA, #memberAA, #memberAAA ');
            for (let i = 0; i < memberB.length; i  ) {
                memberB[i].onclick = function () {
                    //alert(memberB[i])
                    if (memberB[i].className === "open") {
                        memberB[i].className = "";
                    } else {
                        memberB[i].className = "open";
                    }
                    alert(memberB[i].className)
                }
            }
        })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="memberA">A</button>
<button id="memberAA">AA</button>
<button id="memberAAA">AAA</button>

Let me know if this works!

  • Related