Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Cannot empty a nested paragraph

Tags:

html

jquery

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?

like image 277
Max Markson Avatar asked Feb 02 '26 04:02

Max Markson


1 Answers

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

like image 113
Rory McCrossan Avatar answered Feb 04 '26 00:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!