getElementByClassName


#1

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


#2

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


#3

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:


#4

please post an updated version of your code


#5

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:


#6

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


#7

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

Grettings V


#8

Yeee it works :smile:


#9

Good :slight_smile: