javascript - getElementByClassName isn't work -


i have problem why not want work tired time. started learning js. great help

<!doctype html>  <html>      <head>          <title></title>          <meta charset="utf-8">          <meta name="viewport" content="width=device-width, initial-scale=1.0">      </head>      <body>          <img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">          <img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">            <script>              var test = document.getelementsbyclassname("test");              test.onclick = function () {                  alert("test");              };          </script>      </body>  </html>

you need add eventlistener every element. need loop through elements because document.getelementsbyclassname() returns array of elements. can this:

function trigger() {    alert("test");  }    var test = document.getelementsbyclassname("test");    (var = 0, j = test.length; < j; i++) {    test[i].addeventlistener("click", trigger);  }
<!doctype html>  <html>    <head>    <title></title>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">  </head>    <body>    <img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">    <img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">      <script src="script.js"></script>  </body>    </html>


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -