Click here to Skip to main content
15,923,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 positions, 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.

What I have tried:

HTML
<div id="inner">
    <h1> Rewrite using the noun form. </h1><br>
    <p class="input"> </p>
    <p class="input"> </p>
    <p class="input"> </p>
</div>
CSS
#inner {
    text-align: center;
}

.input {
    font-size: 1.5rem;
    margin-top: 30px;
}

.a:nth-child(5) {
    color: green;
}
JavaScript
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);
});
Codepen link: A Pen by Tarun Rathore[^]
Posted
Updated 7-May-20 3:32am
v2

1 solution

Use nth-of-type to select the <p> element, and combine with nth-child to select the word.

For example:
CSS
/* Fifth word of first question: */
#inner p:nth-of-type(1) .a:nth-child(5) {
    color: green;
}

/* Third word of second question: */
#inner p:nth-of-type(2) .a:nth-child(3) {
    color: green;
}

/* Second word of third question: */
#inner p:nth-of-type(3) .a:nth-child(2) {
    color: green;
}
NB: The selector .a:nth-child(5) selects the fifth child element if it happens to also have the class a, NOT the fifth of the child elements which have the class a. There is no nth-of-class selector.

As a result, the question number is included in the word count. The second word of question three is "I", not "did".

:nth-of-type() - CSS: Cascading Style Sheets | MDN[^]
:nth-child() - CSS: Cascading Style Sheets | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900