views:

34

answers:

1

Whats the best way to remove all child elements from a div but leave any text that is directly inside the div in jquery.

I have tried .childre().remove() but this is adding loads of whitespace in firefox and opera. Works fine in ie though.

+1  A: 

Try:

$('#element_id').children().remove().end().text($.trim($('#element_id').text()));

The $.trim is supposed to remove the surrounding whitespace from the text.

Sarfraz
+1; Although you don't need the hash `#` before the `div` in the selector, but works with both: http://jsfiddle.net/NTxx7/ and http://jsfiddle.net/L6G7e/
Giu
@Giu: The hash was meant to show element id, made more meaningful name now. Thanks :)
Sarfraz