user472285
user472285

Reputation: 2674

transform div into h2 span jQuery

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

Answers (4)

Richard Dalton
Richard Dalton

Reputation: 35793

This should do it.

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

http://jsfiddle.net/uPFUu/

Upvotes: 5

700 Software
700 Software

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

Phil
Phil

Reputation: 11175

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

Upvotes: 0

hughes
hughes

Reputation: 5713

Sure!

$('.title').replaceWith('<h2 class="title"><span>'+$('.title').html()+'</span></h2>');

Upvotes: 2

Related Questions