Something like this should do it :
var pattern = /^<br\/>/;
$("<div.column").each(function() {
var $this = $(this),
text = $this.text();
if(text.match(pattern)) {
$this.text(text.replace('<br/>', ''))
}
});
(ignore - left in place so as to make sense of comments below)
EDIT
Try this :
var pattern = /^\n*\s*<br>/;
$("div.column").each(function() {
var $this = $(this),
html = $this.html();
if(html.match(pattern)) {
$this.html(html.replace(pattern, ''))
}
});
DEMO
As @minitech points out, any event handlers and data attached to the original HTML will be lost, so either :
- do the replacement before attaching any event handlers/data
- take measures to re-instantiate event handlers/data after replacement
- delegate event handling to the container element
- do something completely different that is non-destructive - see @minitech's answer.
Second EDIT
After much playing, at last something concise. Try this near 100% jQuery version of @minitech's approach :
$('.column').each(function() {
$.each(this.childNodes, function(i, c) {
return !$(c).filter('br').remove().end().text().trim();
});
});
DEMO
Explanation: The inner loop visits each childNode in turn; its single statement removes the current node if it is a <br>
but allows the loop to progress only if the current node is blank or whitespace. Note judicious use of .end()
to keep everything in one method chain.
Efficiency: Poor - that jQuery method chain must consume a few CPU cycles but that seems a small price to pay.
Readabiity: Close to nada.
Third EDIT
With a mild mod, this will handle any combination of leading whitespace/BRs/HTML comments :
$('.column').each(function() {
$(this.childNodes).each(function(i, c) {
return !$(c).filter('br').remove().end().text().trim();
});
});
The difference from the last version is that the jQuery object $(this.childNodes)
remains unaffected by node removal, whereas the raw this.childNodes
is affected and the .each()
loop doesn't scan properly. At least, that's my best attempt at an explanation.
DEMO