Modify the appearance of every instance of a specific phrase

Looking to give my site title a unique font separate from the rest of the content every time it appears in a heading. This is all for branding purposes. Let's say my custom font is Courier and my company goes by the name SparklePony. For example, if there was a line like,

<h1 class="title">SparklePony Board of Directors</h1>

the word SparklePony would be styled in Courier while the rest of the heading remains in Arial, the default font of my site. (I understand this combination may not look the best.)

I've attempted using jQuery string replacement but I don't want to actually replace the string entirely – instead, I just want to see that specific word in Courier by adding a class or something similar. Whenever I tried replacing SparklePony with

<span class="sparkle-pony">SparklePony</span>
, the whole messy string with tags displayed on my site without effectively adding the desired class.

Is there an error in how I'm implementing my string replace, or perhaps there's a more effective method to style every instance of a particular string?

Answer №1

To achieve this, you can specify the selector as #('h1') or by class.

$('.title').html(function(i,v){    
   return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
​

http://jsfiddle.net/cQjsu/

Answer №2

It appears that without reviewing the actual code (which is crucial in situations like this), my assumption is that you may be utilizing .text() rather than .html(), which would effectively interpret the HTML content.

Answer №3

If a little organization is applied, this could serve as a solid foundation: http://jsfiddle.net/c24w/Fznh4/9/.

HTML

<div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
<button id="clickme">Click to highlight text</button>

CSS

#title{
  font-family: sans-serif;
  font-size: 20pt;
  margin: 30px 0;
}
span.highlight{
  color: #09f;
  font-weight: bold;
}

JavaScript

function highlightText(element, phrase, allOccurrences, caseSensitive){
  var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
  var text = element.innerHTML;
  element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
    return '<span class="highlight">' + match + '</span>';
  });
}

var button = document.getElementById('clickme');
var el = document.getElementById('title');

button.onclick = function(){
  highlightText(el, 'highlight this', true, false);
  button.onclick = null;
};

Answer №4

Consider attempting this approach:

Utilize the following code snippet to modify elements with the class 'title':
$.each($(".title"), function() {
    $(this).html($(this).html().replace("SparklePony", "<span class='sparkle-pony'>SparklePony</span>"));
});

Answer №5

Short and sweet:

let $pageContent = $("main");
$pageContent.html($pageContent.html().replace(/SparklePony/g, "<span class='cool'>SparklePony</span>"));​

Just remember that using $("main") as the selector can be resource-intensive. It's better to choose a more specific parent element.

Check out the demo on JSFiddle here

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

Sliding Content Loading Animation with JQuery from the Right

Is there a way to make a div slide from right to left when clicking on menu items, with an option to close it by sliding back to the right? For example, check out Does anyone have any ideas, demo links, or examples of how to achieve this effect? I came ...

Limit the ng-repeat directive based on the length of the array, using an ng-if condition

<div ng-repeat="badgesData in deptUSersData.badges | limitTo : 7 track by $index"> ........content....... </div> If the length of deptUSersData.badges is more than 8, I want to apply a limit of 7. How can I achieve this? My desired ...

Weird Chrome behaviors with CSS3 animations

I have been working on a CSS3 animation that involves rotating a div with an image in the background. My goal is to have the same animation play at a different speed when the user hovers over the element. Here is the code snippet I have been using: .roc ...

Adding a button to the right of a text-field input in Vuetify app

I need advice on the best way to use Vuetify in order to display a button to the right of a text-field (attached). I've checked the main site for information but couldn't find anything related to this specific scenario. https://i.sstatic.net/Pp ...

The Bootstrap dropdown menu is cut off and not fully visible on mobile devices

I am experiencing an issue with the mobile version of a website where the dropdown menu is not fully visible due to the position of a specific menu item and the number of items in the dropdown. https://i.sstatic.net/HmXeq.png The image below shows how I ...

icon from font-awesome changes color when hovering over

My ASP.NET gridview control includes a font-awesome trash icon in the last column. I'm trying to make the icon change color to red when I hover over it, and then revert back to its default color when I move my mouse away. Here is the code for the te ...

Issue with Zeroclipboard not copying content when initially clicked

My code is experiencing some issues where it doesn't work on the first click, but strangely works on the second click. $("#btnCopiar").on("click",function(){ var clipBoardObj = new ZeroClipboard($("#btnCopiar"), { moviePath: ".. ...

A step-by-step guide to building an API page with Python

Hello everyone! I am just starting out with Vue.js and Python, and I have a question for you. My task is to create a basic webpage using Vue.js on the front end and Python on the backend, with Heidi SQL as my database. My team has requested that I create ...

"Here's a cool trick: A guide on dynamically inserting a value into {% url tag %} using JavaScript within

Incorporating leaflet JS into a Django template, the aim is to display markers on a map where latitude and longitude are sourced from a queryset. Sending the queryset through views and utilizing the Django template language within <script> tags seeme ...

Utilize the jQuery ajaxForm plugin to retrieve the form ID and implement an upload progress bar

On a single page, I have multiple forms that are submitted using ajaxForm and display upload progress. Each form has the same class '.input_form', a unique id, and a hidden input field with the name and class of 'category' containing a ...

The function jQuery.each replaces the existing posts

In the backend of Pimcore, I utilize addresses which are processed by a geocoder to extract latitude and longitude coordinates. These coordinates are then stored in the backend successfully. My next objective is to display all the addresses on a map in th ...

The syntax comparison between CommonJS and AMD modules in a modular AngularJS application

Apologies if this question has already been addressed, but I couldn't find any relevant information. Currently, I'm in the process of refactoring a large AngularJS application by creating components as AMD modules. The build process (grunt) utili ...

Leveraging Scrapy/Selenium for populating fields and conducting searches on LinkedIn's advanced search page

Discover the URL for LinkedIn's advanced search feature: In my attempt to complete fields and submit a form on the LinkedIn advanced search page using Selenium with Python, I encountered a challenge. Whenever I try typing in information for fields l ...

Shift the Search bar to the last position on the navigation bar

I'm looking to relocate the search icon and input field to the end of the navbar. I'm currently using Bootstrap 5.0.2, but I am still new to Bootstrap, HTML, and CSS, so I'm not sure how to accomplish this. I want the width of the search box ...

Unable to receive response from Jquery ajax

Here is the HTML content I have created. <!DOCTYPE html> <html lang="en"> <head> <title>Test page</title> <script language="javascript" type="text/javascript" src="jquery-1.5.1.min.js"></script> ...

How to position div elements side by side using CSS and center them, even on IE8

UPDATE: I have discovered that implementing Bart's solution is the correct one. With a 264px wide div containing the other divs and their 1px borders, I achieved the desired effect. I have updated my code to include his answer. Thank you, Bart. Once ...

Leverage Pinia store in Vue helper functions

I have been working on my Vue.js application and I am looking to implement some helper functions that will utilize a Pinia store within the app. These functions need to be accessible by multiple components. Should I define these helper functions directly ...

Help with parsing text in Javascript

Seeking advice on extracting specific text from a lengthy string. The string can be found at this link: I have a script that can make an HTTP request to retrieve all the text but I need guidance on extracting only certain components from this extensive st ...

A solitary outcome yielded by the JSON iteration

Can anyone help me understand why this code is only returning 1 result instead of 4? I am trying to retrieve all the post titles in the category with ID 121, but it seems to only display the most recent post title. <script type="text/javascript> ...

Retrieving information from React elements

Recently, I ventured into the world of React and started building a mock website for online food ordering. One of my components is called Items, which utilizes props to display all the food items on the webpage. import { useState } from "react"; ...