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:
<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
2
Answers
Edit: Changed
querySelector
toquerySelectorAll
with afor of
to support multipleclass="content__main"
elementsSimple, unsafe way
You could just do the
replace
on theinnerHTML
and set that to the element.Safer way to prevent un-closed tags
A more safe way of doing this, to prevent missing a closing tag is to:
innerHTML
trim()
the spacesp
and add the textdiv
So your problem is that you’re using
.replace
which is a JavaScript default string function on a jQuery object$('.content__main')
– you need to get the HTML value of this as a string to do.replace
.You definitely don’t need jQuery for this, but if you were using it the code could look as follows: