Adam Pietrasiak
Adam Pietrasiak

Reputation: 13224

jQuery wrap text without container

I've got this html

<div>This text is <strong>really</strong> awesome!</div>

I want to wrap inside <span> clicked part of text. So if you click on This text is part you should get

<div><span>This text is </span><strong>really</strong> awesome!</div>

And same with any atomic part of the div

I'm trying to make $('div').click(); event but I can't find out how to detect only the clicked part if it is not wrapped inside something (it's ok with <strong>really</strong> part but not with part before and after it)

Upvotes: 3

Views: 1230

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55678

You might want to look at the .contents() method. This will give you text nodes as well as wrapped nodes, so you can wrap them. To adjust the example from the jQuery docs:

$(".container")
    .contents()
    .filter(function() {
        // get only the text nodes
        return this.nodeType === 3;
    })
    .wrap( "<span></span>" );

It sounds like you want to wrap the content after click, which I think might be quite difficult. If possible, it would be better to wrap the content before the user clicks, then apply a style to the span they clicked - this is much more straightforward. If you use the code above to wrap, you can then apply a handler like

$(".container").on('click', 'span', function() {
    $(this).addClass('clicked');
});

Upvotes: 4

Related Questions