Here is my code, it is attaching an event listener to all elements with the var tag and then triggering a function called getWords()
//The local database
wordBank = [
// {word:"aprobi", translation:"to approve", count:2},
// {word:"bati", translation:"to hit, to beat, to strike", count:1},
// {word:"da", translation:"of", count:1}
];
//getting the var tags and attaching the event listeners
var wordsWritten = document.getElementsByTagName("var");
for (var i = 0; i < wordsWritten.length; i++){
wordsWritten[i].addEventListener("click", getWords())
};
//Getting the details from the word
function getWords() {
if (document.getElementsByClassName("vortarobobelo").length != 0){
var words;
words = document.getElementsByClassName("vortarobobelo")[0].children[0].children;
for (var i =0; i < words.length; i++) {
var localBank = {} //creating the local variable to store the word
var newWord = words[i].children[0].innerText; // getting the word from the DOM
var newTranslation = words[i].children[1].innerText; // getting the translation from the DOM
localBank.word = newWord;
localBank.translation = newTranslation;
localBank.count = 0 //assuming this is the first time the user has clicked on the word
console.log(localBank);
wordBank.push(localBank);
// fireBank.update(wordBank);
}
}
}
It works just fine if I just put the entire getWords() function when I'm using the for loop to attach the eventlisteners but I don't understand why this way doesn't work.
P.S: Is there a better way to break up my code?