0

I would like to make X paragraphs with X sentences and X words. Each of the words are from an array of color names, and I would like for them to be styled in their respective colors. Each of the names are converted into spans and the array is shuffled to avoid repetition. I'm having difficulty styling the spans, though, and I don't know exactly what I'm doing wrong.

I want it to look something like this: Sentences with words styled in their respective colors.

I started by testing a function that makes colorful spans from an array. This works:

namesArr.forEach(function (item, index) {    //For each of the items in the Names array,
     const spanElem = document.createElement("span");     //Create a Span element
     const colorName = namesArr[index].replace(/\s+/g, '').toLowerCase();     //Take a Name and condense it to be a Color Name
     spanElem.style.color = colorName;     //Make the Span's color the Color Name
     let textNodey = document.createTextNode(item);     //Turn Name into some NameText
     spanElem.appendChild(textNodey);     //Put NameText inside the Span
     const spacey = document.createTextNode('\u00A0');     //Create a space
     result.appendChild(spanElem);     //Put Span inside Container 
     result.appendChild(spacey);     //Put Space after Span
});

Then I tested generating words, sentences and paragraphs using items from an array. This works:

function generateText() {                    
     var resultText = generateLorem(3);   //Make so many paragraphs 
     result.innerHTML = resultText;      //Put Text into Container
}

function generateLorem(numofPara) {    //Make Text based on X amount of paragraphs
     var loremText = '';     //initialize full text
     for (var i = 0; i < numofPara; i++) {    //For each of the paragraphs,
          var paragraph = '';     //Initialize a paragraph
          var numSent = 5;     //Make paragraphs X sentences long
          for (j = 0; j < numSent; j++){    //For each of the sentences,
               var sentence = '';     //Initialize a sentence
               var numWords = 5;     //Make sentences X words long
               for (var k = 0; k < numWords; k++) {    //For each of the words,
                    var randomWord = namesArr[i].toString();     //Choose a word based on the Names list
                    var spannedWord = '<span>' + randomWord + '<span/>';     //Make each word a Span  
                    sentence += spannedWord + ' ';     //Add the Span to the Sentence, followed by a Space
                    shuffleArray(namesArr);     //Shuffle Names
               }    //Once you've got your words,
               let capital = sentence.charAt(6).toUpperCase();     //At each sentence, make the first letter capital
               let capital_sentence = '<span>' + capital + sentence.slice(7);     //Make sure the first word is spanned and add the capital
               paragraph += capital_sentence.slice(0,-1) + '. ';     //Remove the last space and replace with period
          }    //Once you've got your sentences,
          loremText += '<p>' + paragraph + '</p>';     //Add each paragraph to the final text
     }    //Once you've got your paragraphs,
     return loremText;     //Generate the Text
}

The next step is to somehow get these functions together. I can't give randomWord or spannedWord a style, because it's undefined. I tried combining the two functions, but using textnodes only gave me a bunch of [object HTMLSpanElement]s. My most recent attempt, avoiding textnodes, gives no console errors, but the words glitch and they're still not colorful:

/*...*/
for (var k = 0; k < numWords; k++) {    //For each of the words...  
     const spanElem = document.createElement("span");     //Create a Span element
     const colorName = namesArr[i].replace(/\s+/g, '').toLowerCase();     //Take a Name and condense it to be a Color Name
     spanElem.style.color = colorName;     //Make the Span's background the Color Name
     spanElem.innerHTML = namesArr[i];     //Let the Span's content be the Name
     sentence += spanElem.innerHTML + " ";     //Add the Span and a space to the sentence
     shuffleArray(namesArr);     //Shuffle the names
}
/*...*/

I also thought about making an array from all the spans and styling them that way, but the spanArray came up as undefined... and, I don't know if it's a good approach, anyway.

(I would prefer pure js and no jquery, if possible).

Here's a codepen.

1 Answer 1

1

The line:

sentence += spanElem.innerHTML + " ";

will get only the "innerHTML" which is just the color name. The innerHTML of <span style="color: indigo">indigo</span> is indigo. Which is why you aren't getting colors at all. To fix that you can change it to outerHTML:

sentence += spanElem.outerHTML + " ";

The next issue with the capitalization: I would personally do that when you create the word rather than when you add the sentence together. If you do it at the word level, you can use the DOM API rather than directly editing the HTML via text:

if (k == 0) {
    spanElem.textContent = spanElem.textContent[0].toUpperCase() + spanElem.textContent.slice(1) 
}

Here I use textContent instead of innerHTML so if you were to add other HTML inside the <span> (for whatever reason), then it would only modify the text instead of the HTML. Plus it is a little clearer when reading the code.

Then after making a few more changes to fix the spacing/periods you get:

function generateLorem(numofPara) {
  var loremText = "";
  for (var i = 0; i < numofPara; i++) {
    var paragraph = "";
    var numSent = 5;
    for (j = 0; j < numSent; j++) {
      var sentence = "";
      var numWords = 5;
      for (var k = 0; k < numWords; k++) {
        const spanElem = document.createElement("span");
        const colorName = namesArr[i].replace(/\s+/g, "").toLowerCase();
        spanElem.style.color = colorName;
        spanElem.innerHTML = namesArr[i];
        if (k == 0) {
          spanElem.textContent = spanElem.textContent[0].toUpperCase() + spanElem.textContent.slice(1);
        }

        if (k + 1 == numWords) {
          sentence += spanElem.outerHTML;
        } else {
          sentence += spanElem.outerHTML + " ";
        }
        shuffleArray(namesArr);
      }

      paragraph += sentence + '. ';
    }
    loremText += "<p>" + paragraph + "</p>";
  }
  return loremText;
}
1
  • And I should have read your last sentence about using arrays. I would personally use only the DOM API. Create a <p> node, then create a <span> node for the sentence, then create another <span> node for the word, stylize it, add the node to the sentence node using sentenceNode.appendChild(wordNode) (developer.mozilla.org/en-US/docs/Web/API/Node/appendChild). Then add the sentence node to the paragraph node. Then you can add that node directly to the HTML. No need to use innerHTML at all. Commented Sep 14, 2023 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.