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

How can you make a dynamic 360 image that responds to mouse movements using three.js?

Is it possible to achieve a three.js effect similar to the one shown here? We have come across solutions that involve drag&drop for camera angle control, but we are interested in having the mouse position dictate where the camera points. For instance, ...

What is the best method for deleting a portion of a string following the final instance of a particular character?

I have a single string that looks like this: "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai" My goal is to truncate the string from the last occurrence of >>. Essentially, I want the resulting string to be: "Op ...

React can easily incorporate CSS from multiple components

I'm experiencing a CSS import issue in my React project. I have a "Home" page that imports Home.css and a "Hero" page that imports Hero.css. Strangely, the styles from Hero.css are being applied to every page in the application without me explicitly d ...

Steps for making a cookie in Node.js using Socket.IO

I'm currently exploring the process of creating a cookie while utilizing socket.io. Although I have successfully figured out how to read cookies, I am struggling to find resources on how to actually create one. socket.on('test', async funct ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

How to pass arguments to the `find` method in MongoDB collections

I've been attempting to pass arguments from a function to the MongoDB collection find method. Here's what I have so far: async find() { try { return await db.collection('users').find.apply(null, arguments); } catch(err) { c ...

What is the best way to simultaneously create a customer and add a card with Stripe?

When attempting to initialize a customer for the first time, I encounter an issue where using a Stripe token more than once raises an error. The process involves a form submission on the client side and handling the token creation on the server side: var ...

What are the steps to designing your own unique custom button with Material-UI?

While Material-UI allows you to utilize withStyles() for creating a Button with a predefined set of styles, I am curious if it is achievable to achieve the same result using props instead. This would ensure that all custom buttons I create automatically ha ...

JavaScript code can be enhanced with HTML comments to improve readability

I have incorporated Google ad into my website using the following code. <script type="text/javascript"><!-- google_ad_client = "pub-"; /*Top 468x15 */ google_ad_slot = ""; google_ad_width = 468; google_ad_height = 15; //--> </script> < ...

Why does the image return an Undefined Value when clicked? Is there a solution to this issue?

Every time I click on an image, I encounter the error message "undefined." Can someone please shed some light on why this is happening and provide guidance on how to successfully retrieve and pass the value to the onclick function in this particular scen ...

How can I make a single <input> element that can handle both files and urls simultaneously?

Is there a way to enable my users to import both local and remote files using just one input field? A possible solution, inspired by Stackoverflow, is to implement tabs: Another approach could be using radio buttons like this: <style> .display ...

Execute the function that has been passed through a data attribute

I am attempting to execute a function using its name, which is passed through a data attribute in the HTML. I have made an attempt with the code below: HTML: <div class="generic-select" data-help-on-shown="genericFunction" > </div> ...

Can you explain the function of this.$nextTick()?

I'm a beginner with Vue.js and I'm trying to wrap my head around the logic of using nextTick in a method. I have two components set up like this: IsTuruIslem.vue <template> ... <t-row> <is-turu-islem-goruntule ref="isTuru ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

Exploring the depths of AngularJS through manual injection

I seem to have misunderstood the tutorial and am struggling to get manual injection working on my project. As I'm preparing to minify and mangle my JS code, I decided to manually inject all my modules and controllers. However, I keep encountering err ...

From navigating getElementByID to tackling getElementsByClassName while constructing multiple select elements: a guide

I am facing an issue with accessing multiple select elements that have the same options in Javascript. Despite having the same class, I am unable to retrieve the options using Javascript. When I attempted switching from getElementById to getElementsByClass ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

React random marker position shifts when the screen size is adjusted

After displaying an image and adding a marker to it, I noticed that the marker's position changes when the screen size is adjusted. Why does this happen? And more importantly, how can I ensure that the marker stays in the same position relative to the ...