-1

** I am learning Dom manipulation and it's my second day... how can I make it as a function that will generate random index of color which I already stored in my array. **

const btn = document.getElementsByClassName("btn");
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • `getElementsByClassName` will return an array like structure i.e. `HTMLCollection`, so you have to use indexing to get the element as `btn[0].addEventListener...`, You can add `eventListener` on HTMLCollection but on HTMLElements. You should read [docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) – DecPK Dec 23 '21 at 09:17
  • 2
    Does this answer your question? [".addEventListener is not a function" why does this error occur?](https://stackoverflow.com/questions/32027935/addeventlistener-is-not-a-function-why-does-this-error-occur) – aerial Dec 23 '21 at 09:18

3 Answers3

1

the getElementsByClassName return an array of elements (cf doc).

to get the first element you should either get the first element of the array document.getElementsByClassName("btn")[0]; or add an id to the button and get it with the document.getElementById('myButton') function

const btn = document.getElementsByClassName("btn")[0];
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>
RenaudC5
  • 3,553
  • 1
  • 11
  • 29
-1

getElementsByClassName will return an array like object of dom elements matching the class. You need to select the entry in this array you want to target :

const btn = document.getElementsByClassName("btn")[0];

see here for details

rabsom
  • 740
  • 5
  • 13
-2

getElementsByClassName returns an array, not a single DOM object. You can try adding an id to the element and use getElementById

Ranjith Jayaram
  • 300
  • 2
  • 13