tags:

views:

70

answers:

4

Jquery - How do I change the parent of an element from an H1 to a P?

I have <h1>heading</h1>, how do I change it to <p>heading</p>

I think I could $.unwrap then $.wrap, but is there a better way?

+1  A: 

This question is pretty close (I would consider it a duplicate) of http://stackoverflow.com/questions/240467/how-do-i-change-an-element-e-g-h1-h2-using-jquery-plain-old-javascript

Using this solution, your answer would resemble

var p = $('h4');
var a = $('<p/>').
    append(p.contents());
p.replaceWith(a);

Test it here: http://jsbin.com/abaja/edit

Rabbott
A: 

I would create a new element with the contents of the H1, then hide the H1.

var contents = $('h1').html();
$('h1').after('<p>'+content+'<p>');
$('h1').hide();
njbair
Instead of hide() which leave it there, why not remove()?
Amy
No reason, either would work fine.
njbair
A: 

HTML:


<h1 id="a">heading</h1>

jQuery:


var $a = $('#a');
var contents = $a.contents();
$a.remove();
$('body').append('<p>' + contents + '</p>');

$.unwrap would remove the parent of the matched element. In other words, if #a were the child of a div, the div would be removed and not the h1.

jsumners
This script however does not replace (as in change it in-place), it appends to the end of body.
Amry
Well, that was just an example off the top of my head. I had no knowledge of the document structure, and I was unaware of the wrapInner() method.
jsumners
+2  A: 
$('h1').wrapInner('<p/>').children().unwrap();
Amry
Oh, I like that one better.
jsumners