Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter", and so on.

<section>
   <h1>Name</h1>

   <p>John</p>
   <p>Jacques</p>
   <p>Peter</p>
   <p>Robert</p>
</section>

Answer №1

To achieve this, follow these steps:

document
  .querySelectorAll('#pColors p')
  .forEach(paragraph => {
    const length = paragraph.innerText.length - 1
    paragraph.innerHTML = `${paragraph.innerText.slice(0, length)} <span class="red">${paragraph.innerText[length]}</span>`
  })
.red { color: red; }
<section id="pColors">
   <h1>Name</h1>

   <p>John</p>
   <p>Jacques</p>
   <p>Peter</p>
   <p>Robert</p>
</section>

Answer №2

The following JavaScript code demonstrates how to manipulate a list of names by splitting each name and adding styling to the last letter:<br>
let list = ['John', 'Jacques', 'Peter', 'Robert'];

for (let i = 0; i < list.length; i++) {
  let name = list[i];
  document.getElementById("list-container").innerHTML += `<p> ${name.substr(0, name.length - 1)}<span style="color: red">${name.charAt(name.length - 1)}<span><p>`
}
<div id="list-container"></div>

Answer №3

Here is a potential solution you can try:

document.querySelectorAll('p').forEach(el => {
  const prefix = el.innerText.substr(0, el.innerText.length - 1);
  const suffix = el.innerText.substr(el.innerText.length - 1);
  el.innerHTML = `${prefix}<span class="colored">${suffix}</span>`;
})

The code uses document.querySelectorAll to target all the <p> elements on the page. Then, it loops through each element using NodeList#forEach. Each iteration extracts all characters except the last one and stores it as 'prefix', followed by extracting the last character and storing it as 'suffix'. The content of the element is then reconstructed using innerHTML, wrapping the single character in a <span> using a template string.

This code assumes that you have CSS styling similar to this example:

.colored {
  color: red;
}

document.querySelectorAll('p').forEach(el => {
  const prefix = el.innerText.substr(0, el.innerText.length - 1);
  const suffix = el.innerText.substr(el.innerText.length - 1);
  el.innerHTML = `${prefix}<span class="colored">${suffix}</span>`;
})
.colored {
  color: red;
}
<section>
   <h1>Name</h1>

   <p>John</p>
   <p>Jacques</p>
   <p>Peter</p>
   <p>Robert</p>
</section>

Answer №4

You have the option to achieve this using CSS.

p::after {
  content: attr(data-end) ;
  color: red ;
}
<section>
   <h1>Name</h1>

   <p data-end="n">Joh</p>
   <p data-end="s">Jacque</p>
   <p data-end="r">Pete</p>
   <p data-end="t">Rober</p>
</section>

Referenced from:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...

Upon clicking a table row, generate a div underneath containing mapped data

My dynamic table is currently being filled with rows based on an array, but I want to display more data in an expanded view when a button in a row is clicked. However, I'm facing challenges as it seems I can't have two table rows within the same ...

Using jQuery's .on() method to dynamically add classes

Why is this method not functioning as expected? My understanding was that by assigning a class to the trigger element when it opens, I could then use that class to close it when the trigger is clicked again. // Trigger for menu $('.menu-trigger' ...

Efficiently managing routes by segmenting them into distinct files

My Express app is structured in the standard Express 4 format, with dependencies at the top, followed by app configuration, routes, and finally the listen function. I'm currently working on organizing my routes into categorized files (e.g., routes/au ...

Utilization of Bootstrap's .container class in various scenarios

As I delve into Bootstrap, the usage of the .container class is provoking some confusion. Most tutorials suggest a structure like this: -.container --.row ---.col- ---.col- However, I came across a different approach in a W3schools example: W3Schools - ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

Show an image when hovering over a dot using CSS - without hovering directly on the image

I'm currently working on a merchandising page that involves photoshopping several products onto a background image. I want customers to be able to hover over a dot positioned on each product to reveal its information and provide a link similar to . Ho ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

Flashing background colors on a website

Can anyone explain why this code won't alternate the background color of my website between two different colors? <script type="text/javascript"> function blinkit() { intrvl = 0; for (nTimes = 0; nTimes < 3; nTimes++) { intrv ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Can you please explain the significance of (session?._id)?

export default NextAuth({ ... callbacks: { session: async ({ session, token }) => { if (session?.user) { session.user.id = token.uid; } return session; }, jwt: async ({ user, token }) => { if (user) { ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

I am experiencing an issue where my JSON array is only returning the last element. Any suggestions on how to

I am facing an issue with my JSON array and Ajax code. Here is the snippet of my code where I upload an Excel file, convert it to JSON, then save it as a string in my database: function exportExcelToTable() { $('#upload-excel-convert').chang ...

Enable users to choose multiple rows at once or alternatively choose by checking the checkboxes

When using Tabulator with the setting table.selectable = true, any cell click selects the row. However, I specifically want rows to be selected only via checkboxes, so I set selectable = false. The issue now is that the checkboxes behave like a radio butt ...

Tips for animating the box-shadow effect using jQuery

Can anyone provide insight on how to animate the box-shadow of multiple elements? I have reviewed previous threads such as this one, but found outdated and non-working solutions. Additionally, I came across the jquery box-animation plugin, which is limit ...

Unable to properly bind events onto a jQuery object

I have been attempting to attach events to jquery objects (see code snippet below), but I am facing challenges as it is not functioning properly. Can someone provide me with a suggestion or solution? Thank you! var img = thumbnail[0].appendChild(document. ...

Pressing the different buttons on a form does not result in the form being submitted

I have a form with multiple buttons that, when submitted, will redirect to a different page and pass along some variables. echo " <form method=\"POST\" action=\"sightWordsTest.php\"> ...

Ways to design siblings that are not currently being hovered over

Is there a way to achieve an effect where hovering over one list item causes all other list items to fade out? I'm searching for a method to style an element that is not being hovered, when one of its siblings is in the hovered state. I've trie ...