dynamic contentand I would like to ...">

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?

+7
source share
4 answers

That should do it.

 $('div.title').replaceWith(function() { return $('<h2>').addClass('title').append($('<span>').text($(this).text())); }); 

http://jsfiddle.net/uPFUu/

+4
source

Of course!

 $('.title').replaceWith('<h2 class="title"><span>'+$('.title').html()+'</span></h2>'); 
+2
source
 $('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()))) }) 

See jQuery: risk not closing tags in constructors

+1
source
 $('.title').html('<span>' + $('.title').html() + '</span>'); 
0
source

All Articles