I'm looking at implementing a simple 2 button toggle on a webpage to switch some selected text between having a H1 heading and H2. The surroundContents method works great, however I'm encountering a problem when trying to replace an existing parent tag element node. I've played around with all sorts of ways trying to do this but not had much success.
The basic functions are below. Using the same selected text and running both of these functions one after the other will result on some output such as the following:
After selecting text of "test text" and then selecting the H1 option:
<h1>test text</h1>
If the same text is selected again and this time the H2 option pressed: <h1><h2>test text</h2></h1>
function surroundSelectedWithH1() {
var element = document.createElement("h1");
// removed code to setup range to save space
if (range) {
range.surroundContents(element);
}
}
function surroundSelectedWithH2() {
var element = document.createElement("h2");
// removed code to setup range to save space
if (range) {
range.surroundContents(element);
}
}
This is fine, and what would be expected, but I'm really looking for a way to remove the original parent heading element so that the heading elements do not become nested (for example - the text is surrounded by either h1 or h2, not both). I did experiment accessing the parentNode etc but did not manage to get this approach functional. I've tried looking at the following parentElement suggestion Getting the parent node for selected text with rangy library however I wasn't able to have rangy write the changed parent element back to the DOM or have a satisfactory way of determining where in the DOM the object was in order to replace it. It quickly became an unwieldy approach and there must be a better option.
I do know that the rangy CssApplier module can handle this situation but I need to work with actual elements and not css.
I also noticed that on the raptor editor which uses rangy for a text editor implementation suffers from the exact same problem when applying headings: http://www.raptor-editor.com/demo
This question was also relevant but this particular element problem can't be handled with execCommand as far as I'm aware - Javascript: how to un-surroundContents range
Any help or advice graciously received.