1

I have a problem why I do not want to work it tired for some time. I just started learning js. Thanks great for the 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>
  • 2
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Andreas Jul 28 '17 at 08:40
  • I can't see your jQuery script inserted anywhere, also what is located in that `script.js` file? – ZombieChowder Jul 28 '17 at 08:42
  • @ZombieChowder the code in the example is vanilla javascript, jQuery isn't required. – John C Jul 28 '17 at 08:48
  • @JohnC huh yeah, I guess it flew right pass me. – ZombieChowder Jul 28 '17 at 08:49

4 Answers4

1

You need to add the eventlistener to every element. So you need to loop through the elements because document.getElementsByClassName() returns an array of elements. You can do it like this:

function trigger() {
  alert("test");
}

var test = document.getElementsByClassName("test");

for (var i = 0, j = test.length; i < 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>
Starfish
  • 3,344
  • 1
  • 19
  • 47
0

I am not a javascript developer, but I Think it should be

var test = document.getElementsByClassName("test")[0];
test.onclick = function (){
    alert("test");
};

as document.getElementsByClassName returns a list.

Gaurang Shah
  • 11,764
  • 9
  • 74
  • 137
0
document.getElementsByClassName("test"); 

returns an array. You have to loop through that array and apply the onclick to each element.

schaffioverflow
  • 510
  • 3
  • 14
  • It returns an array-like live [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection), not an array :) – Andreas Jul 28 '17 at 08:46
  • OK, sorry but at least you can loop through it :) – schaffioverflow Jul 28 '17 at 08:46
  • In most browsers, it actually returns a NodeList Object which is similar to HTMLCollection object. – asmmahmud Jul 28 '17 at 09:22
  • @asmmahmud No it doesn't. The "new" `.querySelector*` methods return [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)s – Andreas Jul 28 '17 at 12:52
  • @Andreas According to https://www.w3schools.com/jsref/met_element_getelementsbyclassname.asp W3School , it returns a NodeList Object. But, according to https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName > Mozilla Developer Network, it returns a HTMlCollection. Which one is correct? – asmmahmud Jul 29 '17 at 07:00
  • @asmmahmud The [specification](https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname) which states: _"The `getElementsByClassName(classNames)` method, when invoked, must return the [list of elements with class names classNames](https://dom.spec.whatwg.org/#concept-getelementsbyclassname) for context object."_ with (from the link) _"The list of elements with qualified name qualifiedName for a node root is the **HTMLCollection** returned by the following algorithm..."_; Hence the MDN is correct and w3schools is not... – Andreas Jul 29 '17 at 07:43
0

As mentioned in the previous answers, the method document.getElementsByClassName return a NodeList Object which is Array like object with numeric indices (0, 1...) and you can loop through it using for .. in loop or Array.prototype.forEach.call method and can attach the event listener to every node.

var tests = document.getElementsByClassName("test");
var node;
for (node in tests) {
  node.addEventListener("click", function(e){
        // do something
   });
}

Or in the following way:

    var tests = document.getElementsByClassName("test");
    Array.prototype.forEach.call(tests, function(node){
      node.addEventListener("click", function(e){
            // do something
      });
   });

Main point is you have to add event listener to every element.

asmmahmud
  • 4,844
  • 2
  • 40
  • 47