Karthikeyan
Karthikeyan

Reputation: 1147

jquery surround selected text and image with span tag

I want to surround selected text and image or texts with multiple tags with span tag in jquery. How can i achieve that, I have seen many examples like the below jsfiddle code. All the examples are done only with text, but now want to surround both text and image with span tag. Thanks in advance

$(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);
});
});

JSFiddle

Upvotes: 2

Views: 1578

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196092

Change your code to use the surroundContents method of the range.

$('.format').click(function () {
    var highlight = window.getSelection(),
        spn = $('<span class="highlight" />')[0],
        range = highlight.getRangeAt(0);

    range.surroundContents(spn);
});

Demo at http://jsfiddle.net/gaby/BGKSN/181
Demo with image at http://jsfiddle.net/gaby/BGKSN/182/

Upvotes: 4

Related Questions