开发者

How to get bold, italic styles within a div

开发者 https://www.devze.com 2023-02-28 07:13 出处:网络
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>

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


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;


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());
});


var element = document.getElementById('whatever');

element.innerHTML = element.innerHTML.replace(/<(strong|em)>(.*?)<\/\1>/g, '$1');

jsFiddle.

Keep in mind any events attached to any children of this div will be lost.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消