3

I'm trying to empty a paragraph inside a div. The paragraph contains others elements: div, text, images, span etc.

<div id="div_id">test
    <p>
        text inside the paragraph
        <div id="text">hello hello hello</div>
        <img src="http://www.mygifto.com/upload/product/26922984_l.jpg" width="200" height="200" alt="Banner" />
    </p>
    hi
</div>
out of div

The simplest solutions should be use the empty() function but it doesn't work at all, it removes only the text inside the paragraph.

$('#div_id p').empty();

I have to specify the div_id because I've others p inside the page and they should not be empty.

Fiddle here

I've tried even with

$('#div_id p').children('*').remove();

but without success. How can I remove all elements inside the paragraph?

Max Markson
  • 800
  • 1
  • 19
  • 34

3 Answers3

9

The problem is because your HTML is invalid. You cannot have a block-level div element inside an inline p.

Change the #text div to a span with display: block on it, and it will work.

<p>
    <span id="text">hello hello hello</span>
    <img src="http://www.mygifto.com/upload/product/26922984_l.jpg" width="200" height="200" alt="Banner" />
</p>
#text {
    border: 1px solid red;
    display: block;
}

Updated fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

The problem is that the HTML code is incorrect, so the elements doesn't end up inside the paragraph. You can't have block elements inside the paragraph.

When the browser has parsed the code and tried to do the best out of it, you end up with two empty paragraphs, one before the content and one after it:

<div id="div_id">test
    <p></p>
        <div id="text">hello hello hello</div>
        <img src="http://www.mygifto.com/upload/product/26922984_l.jpg" width="200" height="200" alt="Banner" />
    <p></p>
    hi
</div>
out of div

Your code to empty the paragraph will work, and it will empty both paragraph elements, but as they are already empty it has no effect, and it doesn't remove the elements that you expect as they are not inside any ofthe paragraphs.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

http://validator.w3.org/check

Paste your code in this and validate. A <div> tag should not be placed inside a <p> tag.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Ramki
  • 166
  • 1
  • 12