Payam Shakibafar
Payam Shakibafar

Reputation: 1125

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.

Upvotes: 0

Views: 791

Answers (3)

rajesh kakawat
rajesh kakawat

Reputation: 10896

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);
        })

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

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

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

You can do this using .wrapInner():

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

Demo: Fiddle

Upvotes: 6

Related Questions