简体   繁体   中英

How to wrap a tag around a text inside a tag?

For example I have this piece of code:

<div class="myclass">Hello everybody!</div>

Then I want to wrap a <p> tag around the text to have this:

<div class="myclass"><p>Hello everybody!</p></div>

How can I do this with jQuery?

I tried this:

$('.myclass').text().wrap('p');

But didn't work.

You can do this using .wrapInner() :

$('.myclass').wrapInner('<p></p>');

Demo: Fiddle

try something like this

        $(function(){
            $('.myclass').wrapInner('<p></p>');
        })

REFERENCE :

http://api.jquery.com/wrapInner/

Alternative

        $(function(){
            var txt = '<p>' + $('.myclass').text() + '</p>'; 
            $('.myclass').html(txt);
        })

Again to remove p tag

        $(function(){
            var txt = $('.myclass').text();
            $('.myclass').html(txt);
        })

A Different approach,

$('.myclass').html('<p>' + $('.myclass').text() + '</p>');

DEMO

To unwrap the tag you simply do like this,

$(".myclass").html($('.myclass > p').text());

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM