santa
santa

Reputation: 12512

Wrap text with HTML

I need to wrap entire content of a an element with a <textarea> tag, minus the element that is clicked.

HTML

<div>
    Some text
    <ul>
        <li>more content</li> 
    </ul>
    <span id="click2wrap"></span>
</div>

JS

$(document).on('click', '#click2wrap', function() {
    var wrapped = $(this).parent().text();
    $(wrapped).wrap('<textarea></textarea>'); 
});

So, my function is currently looking like this and when #click2wrap is clicked it must result in:

<div>
    <textarea>
    Some text
    <ul>
        <li>more content</li> 
    </ul>
    </textarea>
    <span id="click2wrap"></span>
</div>

Upvotes: 0

Views: 81

Answers (2)

Derek Story
Derek Story

Reputation: 9593

Use the wrapInner function. Also, had to add a couple tags to your jquery: JS Fiddle

Because textarea cannot display html tags, you need to get the value of the text area (which has html tags) and re-input that value back into the textarea while stripping the tags.

$(document).on('click', '#click2wrap', function () {
    var wrapped = $('#click2wrap').parent();
    $('#click2wrap').text('');
    $(wrapped).wrapInner('<textarea></textarea>');
    $('textarea').text($('textarea').text());
});

Upvotes: 0

Hayk Manasyan
Hayk Manasyan

Reputation: 506

At first you can't see the parent html code in textarea. To access an id of element you should use # symbol. It means

$(document).on('click', 'click2wrap', function() {
    var wrapped = $(this).parent().text();
    $(wrapped).wrap('<textarea></textarea>'); 
});

should be changed to

$(document).on('click', '#click2wrap', function() {
    var wrapped = $(this).parent().text();
    $(wrapped).wrap('<textarea></textarea>'); 
});

To access to div element use .parent() function and for ul element use .prev() function.

Change

 $(document).on('click', '#click2wrap', function() {
     var wrapped = $(this).parent().text();
     $(wrapped).wrap('<textarea></textarea>'); 
 });

to

$(document).on('click', '#click2wrap', function() {
     var wrapped = $(this).prev();
     $(wrapped).wrap('<textarea></textarea>'); 
 });

Upvotes: 2

Related Questions