Jquery How to Apply CSS to Selected Text

jQuery How do i apply CSS to selected text

I'd recommend the CSS class applier module of my Rangy library for this. It works in all major browsers and for any selection. It will also toggle CSS classes on and off.

Here's an example from another question: How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

Example:

<style type="text/css">
span.red {
color: red;
}
</style>
<script type="text/javascript">
var redApplier;

window.onload = function() {
rangy.init();
redApplier = rangy.createCssClassApplier("red", true);
};

function makeSelectionRed() {
redApplier.applyToSelection();
}
</script>

UPDATE

If using classes isn't an option, you could still use a variation on this, although it's slightly roundabout: you could use Rangy to apply a class, and then use jQuery to find spans with this class and add your CSS to each. Here's an example:

function makeSelectionRed() {
var randomCssClass = "rangyTemp_" + (+new Date());
var classApplier = rangy.createCssClassApplier(randomCssClass, true);
classApplier.applyToSelection();

// Now use jQuery to add the CSS colour and remove the class
$("." + randomCssClass).css({"color": "red"}).removeClass(randomCssClass);
}

jsFiddle: http://jsfiddle.net/z2mdw/2/

Add css style to a specific text using jquery

You can't do that without wrapping the text to an element. But you can do the wrapping with jQuery:

var $test = $('.test').html();
$test = $test.replace(/texts/gi, '<span class="tomato">texts</span>');
$('.test').html($test);

http://jsfiddle.net/r36xjzs7/

This will recreate the whole element though, so it's not that efficient.

Change CSS of selected text using Javascript

The easiest way to do this is to use execCommand(), which has a command to change the background colour in all modern browsers.

The following should do what you want on any selection, including ones spanning multiple elements. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.

UPDATE

Fixed in IE 9.

function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}

function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}

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.

Apply jquery css to contenteditable text selection

How can I use jQuery to apply css to savedRange text selection?

jQuery change text of select depending on selected value

You can get the selected value and check if it equals 'keine'. Then apply gray color:

$('select').on('change', function(){
const value = $(this).val();
if(value === 'keine') {
// apply glay color
} else {
// apply default color
}
});

Demo(It's just a quick sample, can be refactored of course:))

How do I apply css to an element only if it has certain text content in it using jQuery?

this in your code refers to window object.
.text() method returns text content of all the selected elements, the returned value is: foxbrown which is not equal to fox.

You can use :contains selector for selecting elements that contain a specific text:

$('div:contains(fox)').addClass('highlight');

Exact match:

$('div').filter(function() {
return (this.textContent || this.innerText) === 'fox';
}).addClass('highlight');

Apply a CSS class to selected text in Content Editable div

When you click the virtual button, then the selection is gone. You need to bind to mousedown event this way:

function addAnimation() {    selectedElement = window.getSelection().focusNode.parentNode;    $(selectedElement).addClass('grad');}$('.animate-selected').on('mousedown', addAnimation);
.text-field {    background: #333;    color: #fff;    width: 300px;    height: 100px;}
.grad { -webkit-animation: changeColor 8s ease-in infinite; animation: changeColor 8s ease-in infinite;}
.animate-selected{ margin: 2px 0; border: 1px solid blue; display: inline-block; padding: 0 4px; cursor: pointer;}
@-webkit-keyframes changeColor { 0% { color: #ff7473; } 25% { color: #ffc952; } 50% { color: #fc913a } 75% { color: #75D701; } 100% { color: #ff7473 }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="text-field" contenteditable="true">    Hello world. Select this text and press the button</div><div class="animate-selected">    Animate</div>

Javascript/jQuery to apply CSS to element containing specific text/html

$("ol li").filter(function(){
return $(this).text().charAt(0) === '*';
}).addClass('awesome');


Related Topics



Leave a reply



Submit