Manipulate selected text using Javascript

HI, I am trying to develop code in Javascript that adds selected text to a class. What I want to achieve is the ability to highlight text with a custom color.

I want it to look like this:

window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>" 

after executing the above code, the selected background text is surrounded by span tags.

thanks,

Fbr

+4
source share
4 answers

You want to see Range objects, there is a good summary here:

http://www.quirksmode.org/dom/range_intro.html

Browser compatibility will be a problem, but basically you can get the current selection as you suggest, and then convert it to a range and use the Range object's methods to find and split existing DOM nodes and insert your own <span> tag containing the selected text.

This is not entirely trivial and involves serious manipulations with the DOM, but it is a useful item that will help you get around your head. Enjoy it!

+1
source

If you are using jQuery framework , you can try with the following code:

 var your_color = 'yellow'; $('.your-class').css('background-color', your_color); 

If you are not using it, I highly recommend you get started; it makes things a lot simpler, they are very stable and are used by many popular websites, including google and stack overflows.

0
source

Sorry my English, do you mean adding a class to the text?

 function changeClass (elementID, newClass) { var element = document.getElementById(elementID); element.setAttribute("class", newClass); // This is for good browsers element.setAttribute("className", newClass); //For IE< } 

leave all lines harmless if you do this.

0
source

If you're talking about style picks, use ::selection and ::-moz-selection in CSS.

 ::selection { color: ...; background-color: ...; } ::-moz-selection { color: ...; background-color: ...; } 

Alternatively, if you want to select an arbitrary element with a class:

CSS

 .highlighted { color: ...; background-color: ...; } 

Javascript

 yourElement.className = "highlighted"; 
0
source

Source: https://habr.com/ru/post/1305718/


All Articles