0

Suppose we have five divs and having ids like this

1) divId_1

2) divId_2

4) divId_3

5) divId_4

6) divId_5

than how I can apply onclick event for div's which would work for all the div's using javascript in jquery I am sure how to achieve this but not sure how to do this javascript .

like in jquery we can do as below

$('[id^="divId_"]').click(function(){
})

same how we can achieve in javascript .

Shankar
  • 2,890
  • 3
  • 25
  • 40
vikash srivastava
  • 393
  • 2
  • 4
  • 16

2 Answers2

0

This should work:

for(var i = 0; i < document.querySelectorAll('[id^="divId_"]').length; i++){
    document.querySelectorAll('[id^="divId_"]')[i].addEventListener("click", function(){ 
        alert("Hello World!"); 
    });
}
Kushtrim
  • 1,899
  • 6
  • 14
0

You can use .querySelectorAll() and .forEach()

    document.querySelectorAll("[id^='divId_']")
    .forEach(function(el) {
      el.onclick = function() {
        console.log(this.id)
      }
    })
<div id="divId_1">click</div>
<div id="divId_2">click</div>
<div id="divId_3">click</div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • its throwing an error Uncaught TypeError: document.querySelectorAll(...).foreach is not a function at XMLHttpRequest.xhttp.onreadystatechange – vikash srivastava Nov 04 '17 at 07:54
  • At which browser are you trying code? – guest271314 Nov 04 '17 at 07:55
  • i am trying this in chrome brwoser . – vikash srivastava Nov 04 '17 at 08:00
  • The code should return expected result at Chrome. No error is thrown at Chromium 61, see [forEach method of Node.childNodes?](https://stackoverflow.com/questions/36108712/foreach-method-of-node-childnodes) – guest271314 Nov 04 '17 at 08:01
  • @vikashsrivastava You can alternatively use `.call()` to pass the `NodeList` to `.forEach()` `Array.prototype.forEach.call(document.querySelectorAll("[id^='divId_']"), function(el) { el.onclick = function() { console.log(this.id) } })` – guest271314 Nov 04 '17 at 08:04
  • Thanks @guest271314 but still its failing Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[id^‌​='expandIcon_']' is not a valid selector. at XMLHttpRequest.xhttp.onreadystatechange – vikash srivastava Nov 04 '17 at 08:11
  • above error is for below line of code Array.prototype.forEach.call(document.querySelectorAll("[id^‌​='expandIcon_']"), function(el) { el.onclick = function() { console.log(this.id) } }) – vikash srivastava Nov 04 '17 at 08:12
  • How is `XMLHttpRequest()` related to Question? Can you create a stacksnippets or jsfiddle to demonstrate? – guest271314 Nov 04 '17 at 14:24