Reputation: 213
I have a site I'm working on and it uses 'aside' tags, which I'm not getting IE8 to be able to read no matter what I try, even with an HTML5 Shiv. So, I'm wondering, how would you replace existing tags with other tags with jQuery?
For example, if I wanted to change
<aside>
<h3></h3>
</aside>
to
<div>
<h3></h3>
</div>
How would that be done?
Upvotes: 10
Views: 34800
Reputation: 505
Here's a solution that replaces HTML5 block tags, preserving the styling on the divs that replace the HTML5 tags. Simply replacing tags leaves the attributes behind.
$('article, aside, figcaption, figure, footer, header, nav, section, source')
.each(function(){
var el = $(this),
html = el.html(),
attrs = {
"id": el.attr('id'),
"classes": el.attr('class'),
"styles": el.attr('style')
};
console.log('Replacing ' + el.prop('tagName') + ', classes: ' + attrs.classes);
el.replaceWith($('<div></div>').html(html).attr(attrs));
});
(may need a little more work on the source tag, which has "src" and "type" attributes)
Upvotes: 1
Reputation: 73906
Try this:
$('aside').contents().unwrap().wrap('<div/>');
aside
first.unwrap
the contents.wrap
the contents inside a new tag, here a div
.Also, you can do this using .replaceWith()
method like:
$('aside').replaceWith(function () {
return $('<div/>', {
html: $(this).html()
});
});
Upvotes: 33
Reputation: 106
This works for every element in the document and it preserves the contents. Using wraps leads to occurrences of many div
elements if there are line breaks in the contents of the aside
element.
$('aside').each(function() {
$(this).replaceWith("<div>"+$(this).html()+"</div>")
});
Upvotes: 3
Reputation: 1186
This will do the job:
$('aside').replaceWith( "<div>" + $('aside').html() + "</div>" );
Also using the .html() gives a more dynamic approach.
Upvotes: 1