Reputation: 1125
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
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
Reputation: 67197
A Different approach,
$('.myclass').html('<p>' + $('.myclass').text() + '</p>');
To unwrap the tag you simply do like this,
$(".myclass").html($('.myclass > p').text());
Upvotes: 0
Reputation: 73896
You can do this using .wrapInner()
:
$('.myclass').wrapInner('<p></p>');
Demo: Fiddle
Upvotes: 6