Search code examples
jqueryunwrap

Stripping off all p tags inside a div when the div loads


What is wrong with this code? I want so when the div loads all the -p- tags inside div "story_L3" are removed leaving the plain text. simple enough but my code does'nt work, please advice (see example)

<div id="story_L3">
  <p class="one">This is a paragraph inside a p element.</p>
  <p class="two">This is a paragraph inside another p element.</p>
</div>


.one{background-color: yellow;}
.two{background-color: pink;}


$('#story_L3').load(function(){
    $('#story_L3').find('p').contents().unwrap(); 
});

I have also tried:

$('#story_L3').load(function(){
    ($('#story_L3 > p').contents().unwrap(); 
});

and:

$('#story_L3').load(function(){
      if($('#story_L3').find('p').length !== 0){
          $('p').contents().unwrap();     
        }
     });

Solution

  • You don't need to use .load(), directly use .unwrap() code in document-ready handler

    $('#story_L3 p').contents().unwrap();
    .one {
      background-color: yellow;
    }
    
    .two {
      background-color: pink;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="story_L3">
      <p class="one">This is a paragraph inside a p element.</p>
      <p class="two">This is a paragraph inside another p element.</p>
    </div>