Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 228
Adam Pietrasiak Avatar asked Dec 11 '25 08:12

Adam Pietrasiak


1 Answers

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');
});
like image 114
nrabinowitz Avatar answered Dec 12 '25 22:12

nrabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!