harry
harry

Reputation: 25

How to target all elements with Jquery on click

Only first element getting clicked not all, how to get alert on all elements.

Jsfiddle

var btn = document.querySelector(".box i");

btn.onclick = function () {
  alert('hello');
}
<div class="box">
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
</div>
    
    

Upvotes: 1

Views: 663

Answers (3)

ROOT
ROOT

Reputation: 11622

The reason why it only work on the first element is that using .querySelector() method will select only the first element the meet your selector criteria, to be able to select all the elements you have to use .querySelectorAll() which will return a NodeList which can iterate through like this:

var btns = document.querySelectorAll(".box i");

btns.forEach((el, i) => {
  el.onclick  = function () {
    console.log(`Hello! ${i}`);
  }
});
<div class="box">
  <i class="fa fa-address-book-o" aria-hidden="true">1</i>
  <i class="fa fa-address-book-o" aria-hidden="true">2</i>
  <i class="fa fa-address-book-o" aria-hidden="true">4</i>
  <i class="fa fa-address-book-o" aria-hidden="true">5</i>
</div>

Upvotes: 1

Igor Bykov
Igor Bykov

Reputation: 2832

Despite the title of the question, you don't currently use jQuery in your code. So, I provide 2 solutions:

jQuery:

jQuery('.box i').click(function() {
    alert('hello');
});

Pure JS

window.addEventListener('click', function(e) {
    // or e.target.classList.contains('fa-address-book-o')
    if (e.target.className === 'fa fa-address-book-o') { // Better to add some additional class to identify element, like "fireAlert" for instance.
        alert('hello');
    }
});

Alternatively, you could select icons with query selector and add individual event listeners to all of them in a loop, but it's bad for performance & generally not considered a good thing to do.

Upvotes: 1

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4925

Try querySelectorAll for select all then attract onclick to all element

var btnlist = document.querySelectorAll(".box i");
btnlist.forEach(element =>{element.onclick = function () {
  alert('hello');
}});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="box">
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
  <i class="fa fa-address-book-o" aria-hidden="true"></i>
</div>

Upvotes: 3

Related Questions