0

I'm curious if there is an easy way to make this transition with JavaScript.

<div>
  <i>
    <b>
      TEXT
    </b>
  </i>
</div>

To this:

<div>
  <b>
    <i>
      TEXT
    </i>
  </b>
</div>

Now I know that this is possible in longer ways, like creating a new <b> and <i>, placing all of old <b> inside of new <i>, and then new <i> inside of the new <b>, and then replace the child, or similar method. But I'm curious if there's something like node.swapTypeWithParent or swapNodeTypes(b, i).

Rob
  • 14,746
  • 28
  • 47
  • 65
David
  • 4,744
  • 5
  • 33
  • 64
  • 1
    However, I don't think this is meaningful. Because element nesting has many constraints - simply "reverse" a valid dom tree may result in an invalid one. – Leo Jan 01 '15 at 02:14
  • Append the text node to the `i` node, append the `b` node to the `div`, append the `i` to `b` – that’s about as short as it gets, without creating any new nodes. http://jsfiddle.net/p49shh43/ – CBroe Jan 01 '15 at 02:14

3 Answers3

1

No, there's not. Presuming by "longer ways" you mean moving and replacing elements and text with javascript, then that's the way to do it and there are no other shortcuts in javascript.

Rob
  • 14,746
  • 28
  • 47
  • 65
1

You can do this pretty easily with a couple loops

function reverseNest(bottom_level, top_level) {
    var arr = [],
        e = bottom_level,
        f;
    while ((e = e.parentNode) && e !== top_level) {
        arr.push(e);
    }
    arr.push(bottom_level);
    e = top_level || document.documentElement;
    while (arr.length) {
        f = arr.shift();
        e.appendChild(f); // may want to use .insertBefore
        e = f;
    }
}

Here, bottom_level would be your #text node and top_level would be your <div>

Quick DEMO (inspect with console to see reversed tags)

Paul S.
  • 64,864
  • 9
  • 122
  • 138
-1

Here's my jQuery based solution. I think it doesn't get shorter than this!

$('div>*>*').contents().unwrap();

$('div>*').wrap('<b></b>');

I know your example is just a demo for this feature but I still find it trivial that we're swapping <i> elements with <b> elements since the result will be the same semantically and stylistically :)

Mr. X
  • 264
  • 3
  • 6