What is the best way to show JavaScript output with span style?

I have added a translation feature that allows users to switch paragraphs to French when clicked. Each paragraph now has the first word wrapped in a span with a CSS class that enlarges and colors the text. However, I am facing an issue where when switching from English to French, the style of the span is not applied to the French version. How can I make sure that the styling applies to the first word of every French paragraph as well?

function translate_fr(){
  document.getElementById("intro").innerHTML = "At Lion Cuts, we are a cat-exclusive establishment offering a full range of services from grooming to boarding. You and your pet will be pleased to know that only professional, natural, and biodegradable products are used, ensuring no issues with sensitivities or allergies.";     
}
<p id="intro">
    <span class="firstWord">Here</span> at Lion Kuts we are a cat only
      establishment that offers a full range of services 
      from complete grooming, bathing to boarding. You and 
      your pet will be thrilled to know that only professional, 
      natural and biodegradeable products are used, any 
      sensitivities or allergies will not be a problem.
</p>

.firstWord {
    font-family: Alegreya Sans SC;
    line-height: 1;
    font-size: 26px;
    font-weight: bold;
    color: #872741;
}

Answer №1

When tackling this issue, there are numerous approaches you could take. However, considering your specific requirements, the most direct solution might involve a basic search and replace method:

const translatedText = "At Coupe Lion, we are merely a feline establishment offering a full range of services from complete grooming to bathing to boarding. You and your pet will be pleased to know that only professional, natural, and biodegradable products are used, so sensitivities or allergies will not be a problem.";

document.getElementById("intro").innerHTML = translatedText.replace(/^\w+/, '<span class="firstWord">$&</span>');

// Result: <span class="firstWord">At</span> Coupe Lion, we are merely a feline establishment offering a full range of services from complete grooming to bathing to boarding. You and your pet will be pleased to know that only professional, natural, and biodegradable products are used, so sensitivities or allergies will not be a problem

The regex ^\w+ targets the first word, and the $& in the replacement string effectively wraps the matched text in the specified span tag.

Hence, the search locates "At" and substitutes it with

"<span class="firstWord">At</span>"

Answer №2

Attempting to format the first French word in a span similar to the initial English word.

function translate_fr() {
  document.getElementById("intro").innerHTML = `<span class="firstWord">Chez</span> Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème`;
}
.firstWord {
  font-family: Alegreya Sans SC;
  line-height: 1;
  font-size: 26px;
  font-weight: bold;
  color: #872741;
}
<button onclick="translate_fr();">Click me to translate</button>
<p id="intro">
  <span class="firstWord">Here</span> at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable
  products are used, any sensitivities or allergies will not be a problem.
</p>

Answer №3

It seems that even before you press the button, the firstWord Class is already activated. For example,

<span class="firstWord">Here</span>
is displayed at a font size of 26px by default. However, once the button is pressed, the font size needs to be increased.

function translate_fr(){}

Within this function, use querySelector to target the firstWord class and then apply the appropriate styling for that specific action.

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

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

Obtaining Google AAID Using a Mobile Browser (JavaScript)

I've been looking for information online without much success regarding this topic. I am interested in retrieving a user's Google Advertising ID (AAID) through my website when they visit using a mobile browser. I assume it could be done with som ...

Error encountered during the execution of the store method in Ajax CRUD operation

Greetings, I'm encountering an error in my AJAX code every time I try to execute the store function https://i.sstatic.net/SW86I.jpg Below is my controller: public function store_batch(Request $request) { $rules = array( 'batch_name& ...

Retrieve the index of the item that has been selected in a dropdown list

<select ng-click="getIndex($index)" size="14" ng-model="playlist.fileSelected" ng-options="saveFile for saveFile in playlist.playlist"></select> When I try to access $index, it shows up as undefined. Is there a way to retrieve the index of the ...

Steps for placing an image within the boundary of a rectangular div

My div has a width of approximately 730px and a height of 50px. I am looking to place an image at the bottom of the div, exactly where its height ends - after 50px. I have been considering a query to append the image at the bottom. One solution could be ...

What is the best way to add a line next to a specific word in a

For my report, I need to create multiple lines with automated dashes without having to use the SHIFT plus underscore keyboard shortcut. I searched for a solution but couldn't find anything that addressed my specific issue. I envision something like t ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

Comparison of various approaches for invoking JavaScript/jQuery functions

Do the following examples have a performance variation? Example 1: $(window).on('resize', abc); function abc(){ //some abc code } Example 2: $(window).on('resize', function(){ //some abc code }); If so, what are the positives ...

Leveraging Iframes for efficient user authentication within an Angular application

Incorporating an Iframe into one of my templates for authentication has presented certain challenges. Case in point: When a user finishes a training session, they must verify their identity by authenticating with a ping identity server that will redirect ...

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

Accessing a PHP variable within an AJAX handling script

Upon user login, the email is stored in $email (I also tried global $email). Subsequently, a form allows the user to input their roommate's name to search for existing appointments. Incorporating AJAX $("#reserveAPickupAppointmentForm3").submit (fun ...

unable to locate the allong.es variadic function

Encountering an Error node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: undefined is not a function at /home/ubuntu/nodejs/test.js:4:10 at factorial (/home/ubuntu/nodejs/test.js:17: ...

I'm encountering an issue where it appears that my ajax method may not be effectively communicating with my webservice

I am currently working on calling a webservice using an ajax request with the intention of retrieving clinical cases within a specific date range (for example, between 2015-01-01 and 2016-06-08). The webservice functions perfectly when tested individually. ...

What are the steps for encountering a duplicate property error in TypeScript?

I'm currently working with typescript version 4.9.5 and I am interested in using an enum as keys for an object. Here is an example: enum TestEnum { value1 = 'value1', value2 = 'value2', } const variable: {[key in TestEnum]: nu ...

What could be causing useEffect to trigger only after the component has been mounted in NextJS?

I'm currently encountering an issue with my implementation of a useEffect function that is supposed to act like a componentWillMount, but the behavior is not as expected. Within the code for Component (as demonstrated in the Codesandbox provided belo ...

What is the best way to utilize toggle("slide") in order to reveal a message letter by letter?

I am currently experimenting with the `.toggle("slide") function to create an effect where a piece of text appears as though each letter is sliding in. However, I've noticed that instead of a smooth slide, it looks more like the text is flying in abru ...