问题
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