PDA

View Full Version : manipulating documentFragments created from range.extractContents()


herrmiller
06-07-2009, 02:49 PM
if i have a coded string like the following.

<strong>This is |simply </strong><em>some random text</em> <strong>that i typed| just for you.</strong>

if i make a selection like i have indicated above (left of 'simply', right of 'typed'), create a range and extractContents i get a documentFragment like following

<strong>simply </strong><em>some random text</em> <strong>that i typed</strong>

The text nodes that have been cut in the original text are conviently enough also closed. So this seems like a good solution. However, now i want to go through all the <strong> nodes in the fragment and remove them, leaving their text content...

Any good ideas of how to this?

Also, if i select text like this (with the intention of making the selection bold):

<em>This is |simply some</em> random text that i typed| just for you.

i get a fragment like this:

<em>simply some</em> random text that i typed

if the user has chosen to make the selection bold i want to surround Every textNode with <strong> tags and turn the fragment into this:

<em><strong>simply some</strong></em><strong>random text that i typed</strong>

Any good ideas of how to do this? I was thinking of you could somehow use a range object to select each individual textNode and use surroundContents() but i am not sure how to iterate through all the nodes to find the textNodes in the best way...

herrmiller
06-07-2009, 05:37 PM
ok im getting somewhere... i get the range, i use rng.extractContents to get a documentFragment and i have now found my own little way to iterate through all the nodes. but it doesnt really work, and i know why. im using a recursive function (a function that keeps calling itself) but inside i use a for loop, so after a while i figured out the for integer (j = 0) keeps resetting itself, so for more advanced selections it either skips a few nodes or gets locked on the same node (im a bit of a newb so i didnt know that was gonna happen, thought each call to the function would get its own instance of the variable) ... my code is as follow:

var oRTE = document.getElementById('rte1').contentWindow;
var rng = selection.getRangeAt(0);

var fragment = rng.extractContents();

superLoop(fragment);

function superLoop(node) {


if(node.hasChildNodes()) {
// if node has children, loop through all of them and make each of them call this function again
for(j = 0; j < node.childNodes.length; j++) {
superLoop(node.childNodes[j]);
}
} else if (node.nodeType == 3) {
// if the node is a textNode, go in and wrap it with 'em' tag
var newRng = oRTE.document.createRange();
newRng.selectNode(node);
var newNode = oRTE.document.createElement('em');
newRng.surroundContents(newNode);
}
}
rng.insertBefore(fragment);
oRTE.focus();

is there anyway to get around this? or get the same functionality?