Convert div to h2 span jQuery
I have a div with a generated title dynamic title
<div class="title">dynamic content</div> and I would like to convert it like this:
<h2 class="title"><span>dynamic content</span></h2> Can this be done in jQuery?
That should do it.
$('div.title').replaceWith(function() { return $('<h2>').addClass('title').append($('<span>').text($(this).text())); }); Of course!
$('.title').replaceWith('<h2 class="title"><span>'+$('.title').html()+'</span></h2>'); $('div.title').each(function () { $(this).replaceWith($('<h2>').append($('<span>').append($(this).children().remove()))) }) Pay attention to the lines '<h2>' and '<span>' . Just because they are simple tags, can I safely omit end tags. To get your class, you will need 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()))) })