getElementByClassName

Hey

Just wondering I’m tiring to select multiple a button element all with the same class name how do I do this. At the moment I´m just getting an error :frowning:

Here is the HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Caluculator</title>
  <link rel="stylesheet" href="master.css" text="text/css">
</head>
<body>

  <div class="container">
    <p class="product-info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
  </div>

<div class="container">
    <p class="info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
</div>

    <p class="product-info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
</div>

<p class="bill"></p>


<script src="main.js"></script>
</body>
</html>

and here is the JS

var btn = document.getElementsByClass('.plus' );

btn.addEventListener('click', check);

function check() {
  alert('plus +' )
};

Greeting V

here:

var btn = document.getElementsByClass('.plus' );

getElementsByClass is not right, see the docs:

Name is just missing in your case, that will give an error

2 Likes

ok
So I fixed it but now it is throwing an error over btn.addEventLitener(click', );

The error
TypeError: btnPlus.addEventListener is not a function. (In 'btnPlus.addEventListener('click', check)', 'btnPlus.addEventListener' is undefined);

I have checked my spelling and everything even tried changing the class name but it still throws an error :thinking:

please post an updated version of your code

HTML is the same

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Caluculator</title>
  <link rel="stylesheet" href="master.css" text="text/css">
</head>
<body>

  <div class="container">
    <p class="product-info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
  </div>

<div class="container">
    <p class="info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
</div>

<div>
    <p class="product-info"></p>
    <button class="plus">+</button>
    <button class="minus">-</button>
</div>

<p class="bill"></p>


<script src="main.js"></script>
</body>
</html>

JS

var btnPlus = document.getElementsByClassName('plus');

btnPlus.addEventListener('click', check);

function check() {
  alert('plus');
}

Greetings V

p.s. thanks for the fast respons :smile:

you can’t add an eventhandler directly to the object getElementByClassName returns, you will have to make a loop:

1 Like

Thanks for the help I will look into that :slight_smile:

Grettings V

Yeee it works :smile:

Good :slight_smile: <need 20 characters or so >

1 Like