0

I tried to use the code below to change text color to random colors every second but it still didn't work, Is this the correct script when calling element by className

var tx = document.getElementByClassName("this");

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function changeColor(){
  tx.style.color= getRandomColor();
}

setInterval(changeColor,1000);
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • you get elementS (plural). The name of the function is `getElementsByClassName`, not `getElementByClassName`. The console does spot this error, so keep an eye on it when developing JavaScript in the browser. – Federico klez Culloca Feb 13 '21 at 14:41
  • And, let's all agree to [stop using `.getElementsByClassName()](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) in the first place, since event delegation really covers its primary use case. – Scott Marcus Feb 13 '21 at 15:01

2 Answers2

3

Use querySelector instead of getElementByClassName or getElementsByClassName[0].

var tx = document.querySelector(".this");

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function changeColor(){
  tx.style.color= getRandomColor();
}

setInterval(changeColor,1000);
<p class="this">Hello World</p>
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

Class selectors returns ElementList you should change your

var tx = document.getElementByClassName("this");

to

var tx = document.getElementsByClassName("this")[0];

and make sure that "this" is an actual class name in your html code.

Swapnil Soni
  • 965
  • 1
  • 10
  • 26