Selected jQuery surround text with SPAN

The following code should surround the selected text in this Div layer.

$(document).ready(function(){ $('.format').click(function(){ var highlight = window.getSelection(); var spn = '<span class="highlight">' + highlight + '</span>'; $('.conttext').content().replace(highlight, spn); }); }); 

A function of this kind can be used to enable formatting of HTML content corresponding to a DIV.

Something is clearly wrong, although it is currently not working.

http://jsfiddle.net/BGKSN/20/

+6
source share
2 answers

DEMO: http://jsfiddle.net/BGKSN/24/

 $(document).ready(function(){ $('.format').click(function(){ var highlight = window.getSelection(); var spn = '<span class="highlight">' + highlight + '</span>'; var text = $('.conttext').text(); $('.conttext').html(text.replace(highlight, spn)); }); }); 

Later Edit :

Based on the comment, this is a real functional example:

http://jsfiddle.net/BGKSN/40/

 $(document).ready(function(){ $('.format').click(function(){ var highlight = window.getSelection(), spn = '<span class="highlight">' + highlight + '</span>', text = $('.conttext').text(), range = highlight.getRangeAt(0), startText = text.substring(0, range.startOffset), endText = text.substring(range.endOffset, text.length); $('.conttext').html(startText + spn + endText); }); }); 

Docs : https://developer.mozilla.org/en-US/docs/Web/API/window.getSelection

+10
source

Well, firstly, you had the wrong html, something like this
<a href="" class="format">test</div>

Secondly, when you tried to click the test, it did not select the selected text, because this is what happens if you click somewhere when you have the selected text. Therefore, with that in mind, I changed it to $("body").keypress() so that it wraps the selected text in the gap when the key is pressed. Also, some of jQuery and voila code have been fixed, it works!

Check here .

If you fix your anchor tag and your jQuery $(".contenttext").contents() where .contents() does not exist and the function <
$(".contenttext").html($(".contenttext").html().replace(highlight, spn));
it works as expected here .

0
source

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


All Articles