How can I use jQuery to style /parts/ of all instances of a specific word?
To do it reliably you'd have to iterate over each element in the document looking for text nodes, and searching for text in those. (This is what the plugin noted in the question does.)
Here's a plain JavaScript/DOM one that allows a RegExp pattern to match. jQuery doesn't really give you much help here since selectors can only select elements, and the ‘:contains’ selector is recursive so not too useful to us.
// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1) {
findText(child, pattern, callback);
} else if (child.nodeType==3) {
var matches= [];
var match;
while (match= pattern.exec(child.data))
matches.push(match);
for (var i= matches.length; i-->0;)
callback.call(window, child, matches[i]);
}
}
}
findText(document.body, /\bBuyNow\b/g, function(node, match) {
var span= document.createElement('span');
span.className= 'highlight';
node.splitText(match.index+6);
span.appendChild(node.splitText(match.index+3));
node.parentNode.insertBefore(span, node.nextSibling);
});
How can I change the CSS of a specific word?
You can actually do this easily with CSS.
[class*=online] {
color: green;
}
[class*=offline] {
color: red;
}
This CSS selector is looking for any element with an attribute named class
and the *=
is telling the browser to look if the following string exists anywhere within that attribute's value.So any classes with name something-online
or offline-something
or any combination will be matched by this selector.
You can use this same selector with jquery and set the css styles, but using script for this is unnecessary.
Edit:
Thanks to UndoingTech for providing a link to the attribute selectors reference. I'm including it in the answer to make it easier to find http://www.w3schools.com/css/css_attribute_selectors.asp
Attribute selectors are extremely powerful and often overlooked. Since jQuery uses CSS selectors, all attribute selectors work in script as well.
Edit:
Based on clarification on the original question, here is the proper solution for changing the color
style of an element with a particular class based on the text inside of that element.
$(function() {
$(".status").each(function() {
var text = $(this).text().trim().toLowerCase();
if (text === "offline") {
$(this).css("color", "red");
} else if (text === "online") {
$(this).css("color", "green");
}
});
});
This code finds all elements with the .status
class, then .each()
loops through each element and calls the inline function once for each element. This function trims and converts all text to lowercase, and then compares the value of that text with either "offline" or "online" and then sets the css color of the element accordingly. Find and Replace all instances of a word with jquery
Have your replace use a regex with a global replace.
Change:
$(this).html().replace("color","colour")
to:$(this).html().replace(/color/g,"colour");
codepen example Javascript/jQuery change word color by specific some text contains
You could replace all occurrences of your specific text snippets with custom styled html elements:
const yourName = "Groot";
const element = document.querySelector(".me");
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`)
.replace(yourName, `<span class="green-class">${yourName}</span>`);
Alternatively you can also make everything green except the I'm
like this:.me {
color: green;
}
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`);
This way not only Groot
is colored green but everything inside of the div
. That way your JavaScript doesn't need to know the name. How to highlight in yellow a specific part of a string using jquery
You can replace a specific part of the string and wrap it. For better handling you should use a class and css for highlighting some parts.
var text = $('#myspan').text();text = text.replace('+', '<span style="color: yellow;">+</span>');$('#myspan').html(text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span id="myspan">Lorem ipsum dolor sit amet, consectetur adipiscing elit +</span>
How to style the third word inside of a div and use that text in part of the new code?
I would actually use split
to break your span
text into an array of the individual words, manipulate the individual elements and join it back up and add it back into the DOM -
$('.myclass').each(function(index, me) { var words = $(me).text().trim().split(' '); words[0] = '<span class="aspanclass2">' + words[0] + '</span>'; words[2] = '<a href="http://zzzzz.com/' + words[2] + '">' + words[2] + '</a>'; $(me).html(words.join(' '));});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span class="myclass"> one two three</span><span class="myclass"> four fix six</span><span class="myclass"> seven eight nine</span>
Find text string in jQuery and make it bold
You can use replace()
with html()
:
var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
Edit: http://jsbin.com/AvUcElo/1/editI turned it into a lil' plugin, here:
$.fn.wrapInTag = function(opts) {
var tag = opts.tag || 'strong'
, words = opts.words || []
, regex = RegExp(words.join('|'), 'gi') // case insensitive
, replacement = '<'+ tag +'>$&</'+ tag +'>';
return this.html(function() {
return $(this).text().replace(regex, replacement);
});
};
// Usage
$('p').wrapInTag({
tag: 'em',
words: ['world', 'red']
});
Find and replace specific text characters across a document with JS
How about this, replacing @
with $
:
$("body").children().each(function () {
$(this).html( $(this).html().replace(/@/g,"$") );
});
http://jsfiddle.net/maximua/jp96C/1/
Related Topics
Resize Jqgrid When Browser Is Resized
JavaScript Remove "Disabled" Attribute from HTML Input
Does It Make Sense to Use Require.Js with Angular.Js
Select a Complete Table with JavaScript (To Be Copied to Clipboard)
Do We Need Semicolon at the End
Angularjs - Cancel Route Change Event
Differencebetween JavaScript and Ecmascript
Create a <Ul> and Fill It Based on a Passed Array
How to Show a Spinner While Loading an Image via JavaScript
JavaScript Es6 Typeerror: Class Constructor Client Cannot Be Invoked Without 'New'
Rails 5: How to Use $(Document).Ready() with Turbo-Links
Starting File Download with JavaScript
Single Page Application: Advantages and Disadvantages
How to Randomly Generate HTML Hex Color Codes Using JavaScript
Prevent JavaScript Keydown Event from Being Handled Multiple Times While Held Down