javascript - 在 jQuery 中将直接 HTML 兄弟合并为一个

标签 javascript jquery html dom

我需要在包含文本节点的页面代码中将直接的 html 兄弟合并为一个。

<div>some text 
<b>some text</b> som
e text <b>text</b><b> more text</b> some te
xt</div>

这是使用 rangy 和 jQuery 编辑代码后的实际输出,我需要在编辑后清除它,所以它看起来像这样:

<div>some text <b>some text</b> some text <b>text more text</b> some text</div>

我想用 jQuery 来做这件事。我知道函数 unwrap() 和 wrapAll() 但我不能有效地组合它们。 感谢您提供任何线索或帮助!

最佳答案

您需要一个一个地遍历子节点;将节点与前一个节点进行比较,并在必要时进行合并。它可以像你想要的那样复杂;但这是一个开始:

$("div").each(function (i) {
    $(this).find("*").each(function () {
        var that = this.previousSibling;
        if (that && that.nodeType === Node.ELEMENT_NODE && that.tagName === this.tagName) {
            var node = document.createElement(this.tagName);
            while (that.firstChild) {
                node.appendChild(that.firstChild);
            }
            while (this.firstChild) {
                node.appendChild(this.firstChild);
            }
            this.parentNode.insertBefore(node, this.nextSibling);
            that.parentNode.removeChild(that);
            this.parentNode.removeChild(this);
        }
    });
});

Demo here

关于javascript - 在 jQuery 中将直接 HTML 兄弟合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760378/

相关文章:

javascript - Email Validation...提倡使用+,你写这个会有多尴尬?

javascript - 触发文件下载的正确方法?

javascript - jquery 进度条计算秒数并在单击时停止

html - Firefox 与 Chrome 上的绝对定位

facebook - 如何通过类似于预填充推文的 URL 预填充 Facebook 状态消息?

jQuery 设置输入框的值

javascript - 使用下一个按钮在 Meteor 中分​​页

javascript - 链接 Promise 并在它们之间传递参数

javascript - 无法执行点击事件

jquery - header 过期?我如何实现它们以及它们是什么?