Reputation: 113
Am working on a text editor where the content can be in the form of following
<div>some text <strong>bold text</strong> more <em>italic</em></div>
Now on some user click, I have to remove the bold and italic styling from the div.
How can I remove the strong and em tags from a div?
Thanks
Kapil
Upvotes: 4
Views: 4803
Reputation: 324517
Don't use regular expressions or some other kind of text replacement for this. The DOM is a tree. Treat it as such and don't be scared of it. It's by far the safest and least brutal way to handle this kind of thing.
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);
Upvotes: 2
Reputation: 490163
var element = document.getElementById('whatever');
element.innerHTML = element.innerHTML.replace(/<(strong|em)>(.*?)<\/\1>/g, '$1');
Keep in mind any events attached to any children of this div
will be lost.
Upvotes: 3
Reputation: 298106
I'm not sure if you want jQuery, but it handles things like this nicely:
// To remove styles from clicked element.
$('#editor *').click(function () {
$(this).replaceWith($(this).text());
});
Upvotes: 4
Reputation: 20115
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;
Upvotes: 4