jquery - consolidate stacked DOM elements

大城市里の小女人 提交于 2020-01-05 09:05:39

问题


I have HTML that was formatted via a contenteditable div. I am wanting to make it more concise, modern HTML. I can easily replace any b, strong, em, font, etc tags and replace them with spans, but the result produced "stacked" elements.

For instance, I might have:

<span style="font-weight:bold">
    <span style="text-decoration:underline">some text</span>
</span>

And I want to see:

<span style="font-weight:bold; text-decoration:underline">some text</span>

The hard part is it would need to handle:

<span style="font-weight:bold">
    <span style="text-decoration:underline">some text</span> not underlined
</span>

I've done quite a bit of searching and thinking about this, but haven't found anything reasonable.


回答1:


Well, here's a start. Obviously your selector would be more specific than just span.

$("span").each(function(){
    var $this = $(this);
    var $contents = $(this).contents();

    if($contents.length === 1 && $contents.is("span")){
        // only one child (including text nodes) and it is a span, combine
        copyStylesFromParentToChild();  // need to implement this

        $this.replaceWith($this.children());  // replace the parent with the child
    }
});

The only tricky part here is copyStylesFromParentToChild. I don't know any easy straightforward way to copy all styles from one element to another. You can try JavaScript & copy style



来源:https://stackoverflow.com/questions/9271339/jquery-consolidate-stacked-dom-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!