Javascript: Close HTML tags in line

I have a javascript string with HTML code. I show it and I have connected a read / less toggler based on the number of words. The problem is that when I compress the HTML, it may have open tags, suppose that

<p>A computer is a general purpose device that can be <b>programmed</b> to carry out a finite set of arithmetic or logical operations</p> 

when compressed, it becomes

 <p>A computer is a general purpose device that can be <b>programmed...more</p> 

Due to an open bold tag, the following data becomes bold.

I want a javascript solution to close open tags in a string. Any help is much appreciated. Thanks to everyone in advance.

+6
source share
3 answers

use this code

 function fixhtml(html){ var div = document.createElement('div'); div.innerHTML=html return (div.innerHTML); } 

using

 var fixed = fixhtml("<b>some text") 

will return

  <b>some text</b> 
+9
source

"... more" should not even be in the paragraph. Try adding it separately from the paragraph.

Instead, you can wrap everything in a div and reduce it.

 <div class="shrinkable"> <p>A computer is a general purpose device that can be <b>programmed</b> to carry out a finite set of arithmetic or logical operations</p> <span class="see-more">...more</span> </div> 
+1
source

I ran into the same problem and used the following solution. I adapted it to your example.

 var divContent = document.createElement('div'); 

get html from the div you want to compress

 var get_html = $('.shrinkable').html(); 

use innerHTML, this will take care of any open tags in html

 divContent.innerHTML = get_html; 

replace html and add see

 $('.shrinkable').html(divContent.innerHTML).append('<span class="see-more">...more</span>'); 
0
source

All Articles