Yilmazerhakan Yilmazerhakan - 1 month ago 6
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

<div>
using jQuery?

I tried
parent()
,
closest()
but it didn't work.

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

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


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

Answer

Here's one way to do it:

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

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

Comments