0

I have the div, that contains text and images.

<div>
    Some text
    <img src="image.jpg">
     More text
 </div> 

I need to surround selected text with span tag, I know how to do it with simple text, but I don't know how to do it, when there are images inside div. Is there a way to do it?

I need to change the source code, not just text, so that i could add some css styles to selected text.

nnnzzzaaa
  • 37
  • 5

2 Answers2

1

This answer assumes that you would like to use a client technology (here: jQuery) to modify the DOM.

If you want everything wrapped in one span, then use wrapAll():

$( "div" )
  .contents()
  .wrapAll( "<span>" );

If you want only text nodes wrapped in the span, then do some filtering:

$( "div" )
  .contents()
  .filter(function(){return this.nodeType === 3})
  .wrapAll( "<span>" );

At last, if you need every node wrapped in its own span, use wrap() instead wrapAll(). You may combine that with filtering as well.

EDIT

If you need to work with marked text, you can combine this with solution to this question: Get the Highlighted/Selected text

I'd say something like this should work:

function getSelectionObj() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection && document.selection.type != "Control") {
        return document.selection.createRange();
    }
}

$("button").click(function (){
    var o = getSelectionObj();
    if(o.anchorNode == null)
        return;

    var $node1 = $(o.anchorNode);
    var $node2 = $(o.focusNode);

    var $content = $node1.nextUntil($node2).andSelf();

    $content.wrapAll( "<span>" );
});
Community
  • 1
  • 1
OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
0

Have you tried this?

<div>
    <span>Some text</span>
    <img src="image.jpg">
     <span>More text</span>
 </div> 
Collin Alpert
  • 475
  • 6
  • 14