-1

I'm trying to .click() all items in an array, how can I do this?
JQuery cant be used.

var information = document.getElementsByClassName("menu-list-element menu-list-element-basic clickable with-icon-left with-icon-right ");

for (i = 10; i < information.length; i++) {
    //.click() all items in the information array
}
George Kagan
  • 5,913
  • 8
  • 46
  • 50
A. Seidel
  • 43
  • 1
  • 1
  • 7

3 Answers3

5

You can use:

var elements = document.getElementsByClassName("class");

for (var i = 0, len = elements.length; i < len; i++) {
  elements[i].click();
}

Working DEMO.

document.getElementById("btn").addEventListener("click", myFunction, false);

function myFunction() {
  var elements = document.getElementsByClassName("example");

  for (var i = 0, len = elements.length; i < len; i++) {
    elements[i].click();
  }
}
.example {
  width: 50px;
  height: 50px;
  background-color: red;
  cursor: pointer;
  margin: 10px;
}
<input type="checkbox" class="example">
<input type="checkbox" class="example">
<input type="checkbox" class="example">
<input type="checkbox" class="example">
<input type="checkbox" class="example">

<button id="btn">
  Simulate click
</button>

P.S. .click() (as you ask) is not the click event but a javascript function that simulates the click event, from MDN:

The HTMLElement.click() method simulates a mouse-click on an element.

If you want to use click as event:

var elements = document.getElementsByClassName("example");

  for (var i = 0, len = elements.length; i < len; i++) {
    elements [i].addEventListener("click", function() {
        /* Do your stuffs here */
    });
  }

Or with Jquery:

Use jquery .each() instead:

$(".class").each(function(){
  $(this).click();
  /* Or for the event */
  $(this).click(function() {
    /* Do your stuffs here */
  });
});
paolobasso
  • 2,008
  • 12
  • 25
2

You can do the following:

var information = document.getElementsByClassName("...");
var info_items = Array.from(information.children); // Extracts all the child elements and transforms them into an Array

info_items.forEach(item => {
   $(item).click(function() {
      /* 
         Your code for when each item is clicked 
         You can also access data for each item using event.target
      */
   });
});

event.target is a resource from jQuery you can use to access data from the event's target. You can get data like id, className, nodeName, etc.

  • information.children throwing error. It should be var info_items = Array.from(information); // Extracts all the child elements and transforms them into an Array – Balram Singh Aug 05 '21 at 06:13
0

You can use querySeletorAll

var elementList = document.querySelectorAll('.class');

It returns a list, so you have to loop through each element in the list and add the event handler:

for (var i = 0; i < elementList.length; i++) {
    elementList[i].addEventListener(".click", function() {
        // handle click
    });
}