I need to alter some HTML using jQuery – (I have no control over the HTML hence I need to use something client side to make this slight alteration)
If a <br /> is the first element in a div named ‘column’, then I need to remove it.
So:
<div class="column">
<br />text here lorem ipsum blah<br />
Would become:
<div class="column">
text here lorem ipsum blah<br />
Note, I don’t want to get rid of all the <br /> tags, only if a <br /> tag directly follows the opening tag.
I had hoped something like this would work, but no joy
$('<div class="column"><br />').replaceWith('<div class="column">');
Any help appreciated! Many thanks!
Something like this should do it :
(ignore – left in place so as to make sense of comments below)
EDIT
Try this :
DEMO
As @minitech points out, any event handlers and data attached to the original HTML will be lost, so either :
Second EDIT
After much playing, at last something concise. Try this near 100% jQuery version of @minitech’s approach :
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 :
The difference from the last version is that the jQuery object
$(this.childNodes)remains unaffected by node removal, whereas the rawthis.childNodesis affected and the.each()loop doesn’t scan properly. At least, that’s my best attempt at an explanation.DEMO