How to wrap a word in span on user click in javascript

I have: A simple block of html text:

<p>
The future of manned space exploration and development of space depends critically on the
creation of a dramatically more proficient propulsion architecture for in-space transportation.
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy...
</p>

I want to: move a word to a range when the user clicks on it.

Ie User clicked on a manned word than I should get

<p>
The future of <span class="touched">manned</span> space exploration and development of space depends critically on the
creation of a ....

Question: How to do this? Is there a more efficient way that just puts all words in a range at boot time?

PS I'm not interested window.getSelection()because I want to specify a specific style for the affected words, as well as save a set of affected words

Especially for @DavidThomas: an example where I get selected text but don’t know how to wrap it in span .

+3
3

, <span> class .

$( 'p' ).html(function( _, html ) {
    return html.split( /\s+/ ).reduce(function( c, n ) {
        return c + '<span>' + n + ' </span>'
    });
});

, click events <span>

$( document.body ).on('click', 'span', function( event ) {
    $( event.target ).addClass( 'touch' );
});

: http://jsfiddle.net/z54kehzp/


@Jonast92, . . , , .

: http://jsfiddle.net/5D4d3/106/

+6

, , , .

, , .

, , , , 'is', .

, , , - .

:

$(document).ready(function()
{
    var p = $('p');
    p.css({ cursor: 'pointer' });
    p.dblclick(function(e) {
        var org = p.html();
        var range = window.getSelection() || document.getSelection() || document.selection.createRange();
        var word = $.trim(range.toString());
        if(word != '')
        {
            var newWord = "<span class='touched'>"+word+"</span>";
            var replaced = org.replace(word, newWord);
            $('p').html(replaced);
        }
        range.collapse();
        e.stopPropagation();
    });    
});

, @jAndy .

+2

:

$(document).ready(function()
{
    var p = $('p');
    p.css({ cursor: 'pointer' });
    p.dblclick(function(e) {
        debugger;
        var html = p.html();
        var range = window.getSelection() || document.getSelection() || document.selection.createRange();
        var startPos = range.focusOffset; //Prob: isn't precise +- few symbols
        var selectedWord = $.trim(range.toString());            
        var newHtml = html.substring(0, startPos) + '<span class=\"touched\">' + selectedWord + '</span>' + html.substring(startPos + selectedWord.length);
        p.html(newHtml);
        range.collapse(p);
        e.stopPropagation();
    });    
});

We do not close every word in span. Instead, we end the word with just a click.

0
source

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


All Articles