0

I have a container div which has a couple of other divs:

<div class='container'>
 <div>one</div>
 <div>two</div>
 <div>three</div>
 <div>four</div>
</div>

I would like to change all the divs in the container div to ps, so that it looks like:

 <div class='container'>
 <p>one</p>
 <p>two</p>
 <p>three</p>
 <p>four</p>
</div>

How can i accomplish this through jquery? Thanks in advance.

EDIT: I apologize for the lack of clarity, to be precise, i have more than one div container, each of which has other divs inside of it. I don't think the answers already provided will only change the divs contained by div container, but will change all the divs:

<!--block one-->
 <div class='container'>
 <div>one</div>
 <div>two</div>
 <div>three</div>
 <div>four</div>
</div>

 <!--block two-->
  <div class='container'>
 <div>one</div>
 <div>two</div>
 <div>three</div>
 <div>four</div>
</div>

  <!--block three-->
  <div class='container'>
 <div>one</div>
 <div>two</div>
 <div>three</div>
 <div>four</div>
</div>

and so on. what i need is that only the divs inside the div class container are changed into p's:

  <div class='container'>
   <p>one</p>
   <p>two</p>
   <p>three</p>
   <p>four</p>
  </div>


 <div class='container'>
   <p>one</p>
   <p>two</p>
   <p>three</p>
   <p>four</p>
  </div>

there's a small plugin to do it,:

  (function($) {
   $.fn.changeElementType = function(newType) {
    var attrs = {};

    $.each(this[0].attributes, function(idx, attr) {
        attrs[attr.nodeName] = attr.nodeValue;
    });

    this.replaceWith(function() {
        return $(\"<\" + newType + \"/>\", attrs).append($(this).contents());
     });
     }
     })(jQuery);

to use:

$(\"div\").changeElementType(\"p\");

But won't doing that change all the divs to ps? How would i modify it to target only the divs inside the div in class container? Thank you.

4 Answers4

5

You can't really change the tagName, but you can replace the existing divs with p's:

$('.container').children('div').each(function(e, el) {
    $(el).replaceWith( $('<p />', {text: $(this).text()}) );
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
4
$(function() {
    $('.container > div').each(function() {
        $(this).contents().wrapAll("<p>").parent().unwrap();
    });
});
nbrooks
  • 18,126
  • 5
  • 54
  • 66
3

it would be easy if you press Contrl F and open up the finding tool and then click find and replace type "<div>" on the find and "<p>" on the replace and then go through the ones u want and hit replace then it would be done easily without any errors :)

Suits999
  • 369
  • 1
  • 7
  • 25
1

Try this

$(".container").children("div").replaceWith(function(){

   return $("<p />").append($(this).contents());

});
aishazafar
  • 1,024
  • 3
  • 15
  • 35