How can I apply css styles to text that I highlight? Like highlighting in MSWord then clicking bold

Viewed 44

I am creating a graphic user interface with a drop down menu filled with css styles (bold, italics, changing color of words, etc). The problem I am running into is when I apply these styles, it applies to the entire paragraph and not the individual words. How can I code it to recognized what is highlighted and applying the formatting specifically to that.

I would like to apply span to just the highlighted portion. How?

Ex:

    <style>
    .red { 
    color: red; 
    }
    </style>

    <body>
    <p>This <span class="red">is a</span> test.</p>
    </body>

This is the only way I know of to apply span but would like to learn how to have it apply to what the user highlighted. Is there code that detects what user highlighted?

Edit: The goal is to highlight, apply a css style to what is highlighted, remove highlight and style is still there.

4 Answers

If you want to highlight only the span.red, use the ::selection pseudo-element like so:

span.red::selection { background-color: red }
<p>Hello, <span class="red">RED HIGHLIGHT</span>!</p>

Try this out. It should work for you. We have an a span with an id bg-span on which we apply our styling.

<!DOCTYPE html>
<html>
<head>
<style>

#bg-span {
    background-color: #f18973;
}
</style>
</head>
<body>

<p>Set a <span id="bg-span">background</span> color for only a part of a text.</p>

</body>
</html>

I searched and found one solution to get selected/highlighted text by JavaScript and hide it.
You can use this solution and change code to wrap selected text with span and add selected class to that span.

JQuery selector for highlighted text

Good Luck

Related