Is there a way to separate words and specify different CSS colors for each word?

https://i.sstatic.net/a0C02.png

I want to use JavaScript or jQuery to separate a word and apply CSS colors for "Hear (blue)" and "Us (black)".

Below is the inspect element, and since I don't have a file to work on, I will use class names and IDs with inspect element.

For example:

$va = $("#section-56 .mid-content h1 span").text().split("");

alert($va);

How can I make "Hear text blue and Us text black"?

(The above code alert does not seem to be functioning correctly, and I am uncertain if it is accurate).

Here is how I need to extract and split the string.

Answer №1

It is recommended to divide by the space character.

Update

$va = $("#section-56 .mid-content h1 span").text().split("");

With

$va = $("#section-56 .mid-content h1 span").text().split(" ");

Answer №2

Take a look at the code snippet below to see if it can be of assistance.

$va = $("span").text().split(" ");
$("span").html("<span class='blue'>"+$va[0] + "</span> <span class='red'>" + $va[1]);
.red{color:red;}
.blue{color:blue}
<!DOCTYPE html>

<html>

    <head>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  </head>
  <body>
  <span>Hear Us</span>
  </body>
  </html>

Answer №3

To achieve the desired result, you should use the split function with a parameter of space( ). The updated code will look like this:

$(function(){
  var words = $('span').text().split(" ");
  alert(words);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Hear Us</span>

This function will return an array where you can access words[0] as "Hear" and words[1] as "Us".

Answer №4

give this a shot

$(function(){

$va = $("#section-56 .mid-content h1 span").text().split(" ");

    $va[0] = '<span style="color:blue;">'+ $va[0] +'</span>';
    $va[1] = '<span style="color:black;">'+ $va[1] +'</span>';

    $("#section-56 .mid-content h1 span").html($va[0] + " "+ $va[1]);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<section id="section-56">
<div class="mid-content">
<h1>
<span>Experience it</span>
</h1>
</div>
</section>

Answer №5

If you're looking for a creative way to style each word differently, check out this solution I came up with in the past: http://codepen.io/Webpandit/pen/YXdXrg. While it may not be an exact fit for your needs, it could serve as a starting point for customization.

Feel free to modify the code to suit your requirements. It's a fun task that you can take on!

var pText = $('.text');
var words = pText.text().split(' ');
pText.text('');

for(var i=0; i<words.length; i++) {
  pText.append('<span class="textColor">' +words[i] + ' </span>');
}
var textColor = $('.textColor');

// arrays with property values
var colors = ['#000000', '#E843E2', '#666666', '#ff0000', '#00dd00', '#0063FF'];
var fontFamily = ['arial', 'helvetica', 'verdana', 'sans-serif'];
var fontStyle = ['italic', 'normal'];

// function to get random styles from object
var randomStyles = function(obj) {
  return obj[Math.floor(Math.random() * obj.length)];
}

// applying random styles to each word/span element
textColor.each(function(){
  $(this).css('color', randomStyles(colors));
  $(this).css('font-family', randomStyles(fontFamily));
  $(this).css('font-style', randomStyles(fontStyle));
});
.text {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="text">Hello there this is a lorem ipsum text with random styles</div>

After customizing the script to your needs, you can easily extend it to style more words if your header text changes. If you still need help, I can provide further assistance later on.

var pText = $('.text');
var words = pText.text().split(' ');
pText.text('');

for(var i=0; i<words.length; i++) {
  pText.append('<span class="textColor">' +words[i] + ' </span>');
}

var textColor = $('.textColor');

// array with predefined colors 
var definedColors = ['blue', 'black', 'red', 'orange', 'green', 'purple', 'brown', 'pink', 'grey', 'blue', 'black'];

// applying predefined colors to each word/span element
textColor.each(function(index){
  $(this).css('color', definedColors[index]);
});
.text {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="text">Styling three words</div>

UPDATE: The updated snippet now precisely addresses your question. Ensure that the "definedColors" array has at least the same length (or more) as the number of words you are styling. This will apply colors to each word in the order they appear in the array, rather than randomly like the previous version.

Answer №6

The issue arises when the separator used is an empty string ("") rather than a space (" ")

$va = $("#section-56 .mid-content h1 span").text().split(" ");

Once you have extracted the two words as an array using the JavaScript code above, you will need to create new content for the h1 tag with two separate spans.

var newContent = '<span class="color-blue">'+$va[0]+'</span>'+' <span class="color-black">'+$va[1]+'</span>';

$("#section-56 .mid-content h1").html(newContent);

Lastly, make sure to adjust the CSS styles for both words

#section-56 .mid-content h1 .color-blue{color: blue;}

#section-56 .mid-content h1 .color-blue{color: black;}

Alternatively, you can simply include the CSS attributes within the span tags

$va = $("#section-56 .mid-content h1 span").text().split(" ");
var newContent = '<span style="color: blue;">'+$va[0]+'</span>'+'<span style="color: black;">'+$va[1]+'</span>';

$("#section-56 .mid-content h1").html(newContent);

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

Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null. The HTML layout includes: <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <select class="form-control" class="form-control" id="choose_country"& ...

A guide to implementing a For-Each Loop on Argument Array within Functions using Java Script

My code is not functioning properly. I am trying to calculate the sum of numbers provided by the user as arguments. I have attempted to use the Argument Object, but I can't seem to figure out what mistake I've made. // The Argument Object funct ...

Update database upon drag-and-drop using jQuery

I have a dataset (shown below) that undergoes sorting by 'section'. Each item is placed into a UL based on its section when the page loads. My goal is to automatically update the section in the database when a user drags an item to a different s ...

What are the different ways to format a .SQL file in real-time when it is located on an internal website?

In order to upload files to my local server for future reference and training purposes, I am looking for a way to easily format SQL and C# code. I believe there must be a JavaScript library available that can meet these specific needs. My ideal solution ...

Tips for creating a "sticky" button in Angular that reveals a menu when clicked

Is there a way to incorporate a feature similar to the "Get help" button on this website: The button, located in the lower right corner, opens a sticky chat menu. I am interested in adding dynamic information to the button (such as the number of tasks a u ...

Tips for activating a click event on a changing element within a Vue.js application

I am working on creating dynamically generated tabs with a specific range of time (from 8am to 9am). My goal is to automatically trigger a click event when the current time falls within this range. However, I am facing an issue where the ref is being ident ...

Is there a way to add a background image similar to that?

Take a peek at the following site: . Notice how, as you scroll down, the background image appears to be fixed. It's almost like one of the pages acts as a window allowing you to see the background image. How can I achieve this cool effect? ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

Is there a way for me to insert PHP code into a file that has been generated by PHP?

I have encountered an issue where PHP files seem to convert all PHP code into emptiness. Despite creating a PHP file, adding PHP and HTML code to it, and then closing it, the code does not appear as expected in the file. I attempted a solution which is det ...

Conflict with iScroll

When using an HTML5 template in Mobile Safari on iPad, I encountered an issue with a div containing iScroll. Within this div, there is a jQuery function within an if/else statement which tests if the user is tapping outside of the iScroll div and fades it ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...

Alignment issue with content within bootstrap grid

.course-card{ background: white; border-radius: 0.25rem; padding: 1rem 1rem 1rem 1rem; text-align: center; } <div class="row d-flex align-items-center course-card"> <div class="col-md-6 course-progress"> <p>test</p> ...

Getting Observable Centered Text in Angular with Chart.js

I have implemented ng2 charts and chart.js to create a doughnut chart. One of my requirements is to center text inside the doughnut chart, and I have tried the following approach: https://stackblitz.com/edit/ng2-charts-doughnut-centertext?file=src%2Fapp% ...

Creating a unique custom "Ask Seller" button on Ebay can be done by

Currently in the process of revamping a custom sales page for my store and I'm interested in adding a button that says "Inquire With Seller". Despite my efforts to search online, there hasn't been much information available on how to approach thi ...

An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation: function loadHistory() { var detailsForGe ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Leveraging the power of the three.js library on the client-side within a vue.js/n

I'm facing a challenge with incorporating the three.js library (installed via npm) to display 3D models on the client side within my nuxt.js application. Despite multiple attempts, I seem to be hitting a roadblock with the import not functioning prope ...

Trouble with jQuery animate() when using color animations

I am encountering an issue while testing some basic jQuery functionality in Confluence 4.1.9. $("div#test").css("background","#F00"); This code snippet works as expected, however, $("div#test").animate({background:"#F00"}); does not produce the desired ...

The reference to a $scope array in AngularJS has not been properly updated

Check out the code snippet below: var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { $scope.people = [ { id: 1, first: 'John', last: 'Rambo' }, { id: 2, first: 'R ...