当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Rearrange DOM elements according to given standard

问题描述:

I will try do describe the issue:

I'm using contenteditable to edit text in DIV. The standard for elements I need to have in that DIV is:

paragraph:

<p style="someStyles"><span style="someStyles">TEXT GOES HERE</span></p>

empty line:

<p style="someStyles"><span style="someStyles"><br></span></p>

Due to some user text manipulations like copy/paste standard is messed in that DIV like here (ex. of case):

<span style="someStyles">

<p style="someStyles">SOME TEXT HERE</p>

<p style="someStyles">SOME TEXT HERE</p>

</span>

Im looking for a solution that will take messed text elements and rearrange it to given standard I wrote about above, any suggestions ?

After rearranging elements it should look like this:

<p style="someStyles">

<span style="someStyles">SOME TEXT HERE</span>

<span style="someStyles">SOME TEXT HERE</span>

</p>

P.S - I want to make that rearrange function on keyup event while typing and only for whole p element that caret is on.

网友答案:

As I stated in my comment, I can't see a general solution to this, but your specific example could be solved like this. And you can easily make several other conversions based on this one.

The replace function is based on this answer.

// this converts an element to another tag
function replace(thisWith, that) {
    $(thisWith).replaceWith(function() {
        var i, replacement = $('<' + that + '>').html($(this).html());
        for (i = 0; i < this.attributes.length; i++) {
            replacement.attr(this.attributes[i].name, this.attributes[i].value);
        }
        return replacement;
    });
}

function convert() {
    // get SPANs that has Ps inside
    var $spans = $("#content span").has("p");
    $spans.each(function () {
        // change children Ps into SPANs
        replace($(this).children("p"), "span");
        // change parent SPAN into P
        replace(this, "p");        
    });
}

Here is a test jsfiddle.

分享给朋友:
您可能感兴趣的文章:
随机阅读: