Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS replace current tag with a new tag

So, I have some text that looks like:

<div class="content__main">
    <p>This is some text<br>
    This is another line<br>
    Third line goes here<br>
    How about one more</p>
</div>

What I’d like to do is use JavaScript or jQuery to find the <br> tags and replace them with </p><p> tags. The content is auto-generated, so I can’t just add it myself.

I’d like it to look like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="content__main">
    <p>This is some text</p>
    <p>This is another line</p>
    <p>Third line goes here</p>
    <p>How about one more</p>
</div>

I tried:

<script type="text/javascript">
    $(function(){
        $('.content__main').replace(/<br>\\*/g,"</p><p>"));
    });
</script>

But this doesn’t seem to do anything, I think I’m pretty close though, can anyone shed some light on this for me?

Thanks,
Josh

>Solution :

Simple, unsafe way

You could just do the replace on the innerHTML and set that to the element.

const d = document.querySelector('.content__main');
d.innerHTML = d.innerHTML.replace(/<br>\\*/g,"</p><p>");
<div class="content__main">
    <p>This is some text<br>
    This is another line<br>
    Third line goes here<br>
    How about one more</p>
</div>


Safer way to prevent un-closed tags

A more safe way of doing this, to prevent missing a closing tag is to:

  1. Get the innerHTML
  2. Split on newlines
  3. For each line;
    1. Remove all the tags
    2. trim() the spaces
    3. Create a p and add the text
    4. Insert that to the original div
const d = document.querySelector('.content__main');
const old = d.innerHTML;
d.innerHTML = '';

for (let line of old.split("\n")) {
  let cleaned = line.replace(/<\/?[^>]+(>|$)/g, "").trim();
  if (cleaned !== '') {
      let newE = document.createElement('p')
      newE.innerHTML = cleaned;
      d.appendChild(newE);
  }
}
<div class="content__main">
    <p>This is some text<br>
    This is another line
    Third line goes here<br>
    How about one more</p>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading