Question

I use Blogger as my blogging platform. Annoyingly, hitting enter in the Rich Text Editor creates <br /> (line break) tags instead of <p></p> (paragraph tags). Unfortunately I have found no means of switching this within the Blogger platform.

So my solution is to use jQuery to replace every even <br /> tag with an opening <p> tag and every odd <br /> with a closing </p> tag like below.

<br /> (replace with <p>)
Some initial paragraph
<br /> (replace with </p>)
<br /> (replace with <p>)
Some second paragraph
<br /> (replace with </p>)
<br /> (replace with <p>)
Some third paragraph
<br /> (replace with </p>)

To do this, I wrote the below jQuery.

$("br").each(function(i){
    if (i % 2 === 0){
        $(this).replaceWith("<p>");
    } else {
        console.log("odd break");
        $(this).replaceWith("</p>");
    }
})

However, instead of getting my results above, I instead found that each <br /> tag was replaced with both an opening and closing tag <p></p>

Any suggestions as to how I can go about doing this?

Thanks!

(And please do not suggest that I switch to another blogging platform that actually does what I intend. I do not wish to do that nor does it actually answer my question.)

Was it helpful?

Solution

You can only append full nodes to the dom. One solution would be to wrap the text nodes in <p> elements and remove the <br>s:

http://jsfiddle.net/MYFQV/

$('#content').contents().filter(function() {
   return this.nodeType == 3 && $.trim($(this).text()).length > 0; 
}).wrap('<p/>');
$('#content br').remove();

OTHER TIPS

var s = $('#content').html();
var i = -1;
s = s.replace(/<br \/>/gi, function() {
    i++;
    return i % 2 == 0 ? '</p>' : '<p>';
}, 'gi');
$('#content').html(s);

This reads the HTML as text, uses a regular expression to replace each instance of <br /> with the correct opening or closing tag, and then writes the HTML string back to the page.

You are making a confusion between the HTML tag soup and the DOM.

When a page is accessed inside the browser, it (the browser) parses the HTML code (tags) and creates DOM elements. It will not care very much about the validity of your HTML, for example:

<div id="parent>
  <p>
  One paragraph
  <div>Split</div>
  Another paragraph
  </p>
</div>

Will be turned into a tree with one parent and 3 children like this:

#parent 
  p > text(One Paragraph)    
  div > text(Split)
  text(Another paragraph)

What you could do instead is extract the text between the br tags and place it in paragraphs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top