I want to create a typing game for my portfolio project . I am new to programming .
I want to render every random word in a div and every character wrapped in a span tag inside that div.
i achieved rendering the divs but wrapping the characters inside span tags seems impossible . i tried many ways but couldn’t get it to work.
closest i got is this function which takes the word and parent as a param and creates spans in that parent element
function spanifyWords(word, parent){
for (i=0 ; i< word.length; i++){
let newSpan = document.createElement("span");
newSpan = parent.appendChild(newSpan);
newSpan.innerHTML += word[i];
}
}
if i call this function with for example
spanifyWords("hello", wordsContainer) ;
then it creates 5 span tags which each char inside the main div .
this one works fine as long as i dont call it in other function which renders divs inside the main div(wordsContainer).
function renderDivs(n){
for (i=0; i<n; i++){
let randomIndex = Math.floor(Math.random()*wordsCount)
let randomWord = newArray[randomIndex];
let newDiv = document.createElement("div")
newDiv = wordsContainer.appendChild(newDiv)
newDiv.innerHTML += spanifyWords(randomWord, newDiv); // this needs attention
}
}
my guess is that I’m doing something wrong at the last line of second function . either function is not able to configure the parent or Javascript innerHTML doesn’t take a function as a value.
can someone please tell me what is wrong with the second function?
2
Answers
The
spanifyWords
function already adds the span elements to the container, so there is no need to set theinnerHTML
at all (in fact, you were setting it toundefined
asspanifyWords
does not return anything). Directly usespanifyWords(randomWord, newDiv);
instead.Furthermore, declare each loop counter with
let i = 0;
so that it is scoped to the block instead of global.i = 0
should belet i = 0;
otherwise it’s set to the global scopenewSpan = parent.append(newSpan);
just useparent.append(newSpan);
wordsContainer.append(newDiv);
without theinnerHTML =
– that task is already done in thespanifyWords
functionconst
where dueHere’s also a slight variation on the above code: