I'm looking for some ideas for the most efficient way to remove trailing html <br/> tags using javascript or jquery.
RULES:
- The br, at the front and end must be removed.
- It must remove non-closing and self-closing br tags.
- All br within the textual content must remain untouched.
THE HTML:
<div class="generatedContent">
<br>My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here<br/>
<br>
<br>
<br>
<br>
<br>
<br>
</div>
THE DESIRED OUTPUT:
<div class="generatedContent">
My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here
</div>
Can't understand why you'd want to to use regular expressions for this, as most answers are. Using DOM methods is easy here:
function isBrOrWhitespace(node) {
return node && ( (node.nodeType == 1 && node.nodeName.toLowerCase() == "br") ||
(node.nodeType == 3 && /^\s*$/.test(node.nodeValue) ) );
}
function trimBrs(node) {
while ( isBrOrWhitespace(node.firstChild) ) {
node.removeChild(node.firstChild);
}
while ( isBrOrWhitespace(node.lastChild) ) {
node.removeChild(node.lastChild);
}
}
$(".generatedContent").each( function() {
trimBrs(this);
} );
Try this:
var everything = $('.generatedContent').contents();
for(var i=everything.length-1;i>0;i--)
{
if((everything.get(i).tagName == 'BR'
&& everything.get(i-1).tagName == 'BR')
|| (everything.get(i).textContent.match(/\w/)==null))
$(everything.get(i)).remove();
else
break;
}
It seems to work in FF and IE7, that I've tried.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With