Yilmazerhakan Yilmazerhakan - 4 months ago 13
HTML Question

Remove sequential <br> in div filled by CMS users via rich text editors

I have div-area which is filled by CMS users and sends data via a rich text editor. How can I remove sequential br tags more than two in a

using jQuery?

I tried
but it didn't work.

For example, a CMS user added this HTML code using a rich text editor.

<div class="cms-data">
<a href="/uploads/755/a1.xls" target="_blank">xls</span></a>

Edit: I added a class name to the
, cms-data.


Here's one way to do it:

$("#starting-point").find("br").each(function() {
    if (this.previousSibling && this.previousSibling.nodeName.toUpperCase() == 'BR') {

That finds all of the br elements within the given container (in my case, the element with the id "starting-point"). Then it loops through them in document order. If we have one that has an immediate previous sibling that's a br element, we remove it. We leave it alone if the thing just in front of it is not a br element (such as a text node, or a non-br element). Note that this doesn't consider <br> <br> to be two consequtive elements, because there's a space between them.

Live Example | Source