1

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.

jopke
  • 1,186
  • 6
  • 18
  • You're looking to do this on the fly in javascript? – James Montagne Feb 14 '12 at 03:37
  • @JamesMontagne Yes. The user enters text into a "contenteditable=true" div and I want to clean it up before it is sent on. I'm not looking to keep the div's HTML clean, just need to do it once the user is done, which is an event I already capture. – jopke Feb 14 '12 at 03:41
  • @jopke - I had a similar requirement where the contenteditable div was to be cleaned up on a submit button. To simplify things I would set useCSS to false, clean up html soup (take a look at solution 3 at: http://stackoverflow.com/questions/16226671/consolidate-stacked-dom-formatting-elements-contenteditable-div ) and then use regex to quickly convert the b/span/s/u/i/em tags to appropriate CSS equiv. Note that Solution3 will order the formatting for all nodes (so you can reorder the formatting to how you want to process via regex). – Mike Wolfe Apr 29 '13 at 16:48

1 Answers1

0

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

Community
  • 1
  • 1
James Montagne
  • 77,516
  • 14
  • 110
  • 130