I have a code in mind when if a website first open, a certain text would go in a loop where it display the words that are in a list. When I attempt to run the code, the console described that the "text[num]" has an error and, therefore, couldn’t run the code. This is the following code:
var num = 0;
var texts = [
"1 Element",
"2 Element",
"3 Element",
"4 Element",
"5 Element"
];
window.onload = function() {
changingTitleLoop();
}
function changingTitleLoop(){
setTimeout(function() {
changeText();
// Call the loop function again to create an endless loop
num++;
changingTitleLoop();
}, 3000);
}
function changeText(){
if(num >= texts.length){
num = 0;
} else {
var something = document.getElementById("changingText");
something.textContent = texts[num];
}
}
I tried changing the tag "textContent" to "innerHTML", however it didnt fix the problem. Is there something I’m missing in the code? any mistakes?
2
Answers
UPDATE: I was reviewing the code when I realized that I needed to specify the specific "array" or "position" of the essential element since I was using getElementByIDName(). In this case, I decided to use getElementsByClassName() to see if there were much of differences.
As it turns out, I would need to use either document.getElementsByClassName("changingText")[0] or replace document.getElementsByClassName("changingText") with document.querySelector(".changingText"). As a result, the properties of are found and run as JavaScript was able to change their textContent.
The code works as followed:
After checking the property of the element figuring if there were CSS properties that may or may not affect JavaScript, it appears that the following HTML is still valid even with other Classes and Id tagged.
I simulated your code, and I didn’t encounter any errors. However, I did change a few lines because I noticed it is skipping over items in the array (I don’t know if it is intentional) and also transforms the recursive function into an interval.
Please try to be more clear (by stating the full message), instead of saying "the console described that the "text[num]" has an error". There is a high chance that there is an error being caused by other code, preventing your functions to start.