How to change the color of a specific word of each array object?

By using the following code I am able to change the color of the word occurring at fifth position.
I want to change the color of words occurring at different places, e.g., fifth word of first question, then third word of second question, and second word of third question and so on.
How can I achieve that ? Could you please help me with the code.

<div id="inner">

    <h1> Rewrite using the noun form. </h1><br>

    <p class="input"> </p>

    <p class="input"> </p>

    <p class="input"> </p>

</div>

var questions = [

        {
            question: "1. I requested my boss.",
            answer: "She made a request to my boss.",
        },

        {
            question: "2. He prepared for exams.",
            answer: "He made preparations for exams.",
        },

        {
            question: "3. I did my job perfectly.",
            answer: "I did my job with perfection.",
        },
    ];

    $.each(questions, function(i, x) {

        arr = '<span>' + x.question.split(/\s+/).join('</span> <span class="a">') + '</span>';

        $('.input').eq(i).append(arr);

    });

Here is codePen link:

Why do this with Javascript when HTML would do the job for you?

question: "1. I requested my boss.",
question: "1. I <span class='a'>requested</span> my boss"
1 Like

How stupid do I feel!! :banghead:

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Practice Sheet</title>

<style>
#quiz {
  text-align: center;
}

.question,
.answer {
  font-size: 1.2rem;
  margin-top: 1rem;
}

.answer {
  color: red;
  transition: opacity 1s linear;
}

.highlight-word {
  font-weight: bold;
  color: Indigo;
}

.hidden {
  visibility: hidden;
  opacity: 0;
}
</style>
</head>
<body>
  <div id = 'quiz'>
    <h1>Rewrite using the noun form.</h1>
    <div class = 'questions'>
    </div>
  </div>
  <button id='show-answers'>Answers</button>
<script>
const questions = [
  // Note: no comma after the last properties
  {
    question: "1. I requested my boss.",
    answer: "She made a request to my boss."
  },

  {
    question: "2. He prepared for exams.",
    answer: "He made preparations for exams."
  },

  {
    question: "3. I did my job perfectly.",
    answer: "I did my job with perfection."
  }
];

/**
  regexToMatch: Creates a simple regular expression from an array
  The Brackets mean capture the match. The '|' means 'or'
  Example: ['boss', 'exams', 'job'] => /(boss|exams|job)/ ( boss or exams or job )
*/

const highLightWord = function( sentence, toMatch = [] ) {

  const regexToMatch = new RegExp('(' + toMatch.join('|') + ')')

  // $1 is a reference to the match we captured inside of the brackets.
  return sentence.replace(regexToMatch, "<span class='highlight-word'>$1</span>")
}

/**
  questions.map returns an array of strings
  Example: [ {question: 'Why?', answer: 'Because...'}, {...} ] =>
    [ "<p class = 'input'>Why?</p><p class = 'hide-answer'>Because...</p>",
      "<p class = 'input' ..... " ]
  The resulting array is then concatenated into one string using join('')
*/

const createQuestionsHTML = function( questions, toMatch = [] ) {

  const html = questions.map( function( { question, answer } ) {
    return `
      <p class = 'question'>${highLightWord( question, toMatch )}</p>
      <p class = 'answer hidden'>${answer}</p>`
  }).join('')

  return html
}

const divQuestions = document.querySelector('div.questions');
const button = document.getElementById('show-answers');

divQuestions.insertAdjacentHTML(
  'afterbegin',
  createQuestionsHTML(questions, ['boss', 'exams', 'job'])
)

button.addEventListener('click', function showAnswers( event ) {

  divQuestions.querySelectorAll('.answer').forEach( function (elem) {
    elem.classList.remove('hidden');
  })
  // clean things up and remove the event listener
  button.removeEventListener('click', showAnswers, false)
}, false)
</script>
</body>
</html>

Test ouputs

console.log(highLightWord('Test this sentence for a match', ['sentence', 'trifle', 'cat']))
// Output: Test this <span class='highlight'>sentence</span> for a match

console.log(createQuestionsHTML( questions, ['boss', 'exams', 'job'] ))
/* Output:
    <p class = 'question'>1. I requested my <span class='highlight'>boss</span>.</p>
    <p class = 'answer hidden'>She made a request to my boss.</p>
    <p class = 'question'>2. He prepared for <span class='highlight'>exams</span>.</p>
    <p class = 'answer hidden'>He made preparations for exams.</p>
    <p class = 'question'>3. I did my <span class='highlight'>job</span> perfectly.</p>
    <p class = 'answer hidden'>I did my job with perfection.</p>
*/
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.