How to get bold, italic style in a div

I am working on a text editor where the content may be in the form of the following

<div>some text <strong>bold text</strong> more <em>italic</em></div> 

Now click on some users, I need to remove the bold and italic style from the div.

How to remove strengths and tag tags from a div?

thanks

Capil

+4
source share
4 answers

HTML

 <div id="foo"> <div>some text <strong>bold text</strong> more <em>italic</em></div> </div> 

Js

 var t = document.getElementById('foo').innerHTML; t = t.replace('<strong>', ''); t = t.replace('</strong>', ''); t = t.replace('<em>', ''); t = t.replace('</em>', ''); document.getElementById('foo').innerHTML = t; 
+4
source

I'm not sure if you want jQuery, but it does a great job of such things:

 // To remove styles from clicked element. $('#editor *').click(function () { $(this).replaceWith($(this).text()); }); 
+4
source
 var element = document.getElementById('whatever'); element.innerHTML = element.innerHTML.replace(/<(strong|em)>(.*?)<\/\1>/g, '$1'); 

jsFiddle .

Keep in mind that any events associated with any children of this div will be lost.

+3
source

Do not use regular expressions or any other type of text replacement for this. DOM is a tree. Consider it as such and do not be afraid of it. This is by far the safest and least brutal way to deal with such things.

 function removeElements(container) { var elements = container.getElementsByTagName("*"); // Make an array of the strongs and ems var strongsAndEms = []; for (var i = 0, len = elements.length; i < len; ++i) { if (/^(strong|em)$/i.test(elements[i].tagName)) { strongsAndEms.push(elements[i]); } } // Remove the strongs and ems for (var j = 0, el, child; el = strongsAndEms[j++]; ) { while ( (child = el.firstChild) ) { el.parentNode.insertBefore(child, el); } el.parentNode.removeChild(el); } } var div = document.getElementById("foo"); removeElements(div); 
+2
source

All Articles