Reputation: 2674
I have a div with a generated title dynamic title
<div class="title">dynamic content</div>
and i would like to transform it like so:
<h2 class="title"><span>dynamic content</span></h2>
Would that be doable in jQuery?
Upvotes: 7
Views: 2011
Reputation: 35793
This should do it.
$('div.title').replaceWith(function() {
return $('<h2>').addClass('title').append($('<span>').text($(this).text()));
});
Upvotes: 5
Reputation: 87833
$('div.title').each(function () {
$(this).replaceWith($('<h2>').append($('<span>').append($(this).children().remove())))
})
Notice my strings '<h2>'
and '<span>'
. Only because they are simple tags can I omit the end tags safely. To get your class you will want one of
$('div.title').each(function () {
$(this).replaceWith($('<h2>').addClass('title').append($('<span>').append($(this).children().remove())))
})
or
$('div.title').each(function () {
$(this).replaceWith($('<h2 class="title"></h2>').append($('<span>').append($(this).children().remove())))
})
See jQuery: Risk of not closing tags in constructors
Upvotes: 1
Reputation: 5713
Sure!
$('.title').replaceWith('<h2 class="title"><span>'+$('.title').html()+'</span></h2>');
Upvotes: 2