How can I Strip all regular html tags except , (>

前端 未结 4 565
误落风尘
误落风尘 2020-12-21 02:29

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submit

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 02:55

    Smerny's answer is working well except that the HTML structure is like:

    var s = '
    Link Span
  • '; var $s = $(s); $s.find("*").not("a,img,br").each(function() { $(this).replaceWith(this.innerHTML); }); console.log($s.html());

    The live code is here: http://jsfiddle.net/btvuut55/1/

    This happens when there are more than two wrapper outside (two divs in the example above).

    Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.

    This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.

    A working solution is simple: loop from the most inner element towards outside:

    var $elements = $s.find("*").not("a,img,br");
    for (var i = $elements.length - 1; i >= 0; i--) {
        var e = $elements[i];
        $(e).replaceWith(e.innerHTML);
    }
    

    The working copy is: http://jsfiddle.net/btvuut55/3/

提交回复
热议问题