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?
This should do it.
$('div.title').replaceWith(function() {
return $('<h2>').addClass('title').append($('<span>').text($(this).text()));
});
http://jsfiddle.net/uPFUu/
Sure!
$('.title').replaceWith('<h2 class="title"><span>'+$('.title').html()+'</span></h2>');
$('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
$('.title').html('<span>' + $('.title').html() + '</span>');
精彩评论