Forum Moderators: open

Message Too Old, No Replies

Editable DIV super normalize. Strip out HTML markup

Remove pasted HTML markups

         

wwmark

1:58 am on May 28, 2010 (gmt 0)

10+ Year Member



Hey folks,

I have editable DIVs which I'm using to type in raw text into a web page and then push it back to a server for storage. The problem is whenever you select text from somewhere such as another web page you will also end up pasting the markup of that new text as well, i.e. the FONT and PRE tags (if PRE was wrapping your selected text) will be pasted. It ends up mucking up the text in your DIV area with loads of 'alien' formatting and is a pain to highlight around the pasted text to try and clear it.

What I ended up doing is calling a javascript function every time I pasted into the DIV. That function hunts through the HTML DOM and if it found a text element or a BR element it kept it, pushing the element all the way up the DOM tree to the enclosing DIV. Then once the FONT and PRE elements were empty of content it then nuked them.

It's all compliant stuff, no use of deprecated innerHTML etc, so it'll be future proof I think. Hope folks find it useful. I'm posting it here to have google index it for others.

ta,
Mark.



<DIV ID="notes" NAME="notes" onPaste="clean_pasted_content('notes');">



function clean_pasted_content(area_div) {
var div_to_clean = document.getElementById(area_div);
var do_again = 1;
while (do_again) {
do_again = 0;
if (div_to_clean.hasChildNodes()) {
for (var x = 0; x < div_to_clean.childNodes.length; x++) {
var child_node = div_to_clean.childNodes[x];
if (child_node.nodeType == 3) { continue; }
if (child_node.nodeType == 1) {
if (child_node.nodeName == 'BR') { continue; }
do_again = 1; // Not a BR, do stuff and re-scan
no_elements(div_to_clean);
}
}
}
}
div_to_clean.normalize();
}

function no_elements(parent) {
var parent_type = parent.nodeType;
if (parent.hasChildNodes()) {
for (var x = 0; x < parent.childNodes.length; x++) { // scan all children nodes
var child_node = parent.childNodes[x];
if (child_node.nodeType == 3) { // move text nodes up if not already in the DIV
if ((parent_type == 1) && (parent.nodeName != 'DIV')) {
move_element_up_dom(parent, child_node);
continue;
}
}
if (child_node.nodeType == 1) {
if ((child_node.nodeName == 'BR') && (parent.nodeName != 'DIV')) {
move_element_up_dom(parent, child_node);
} else {
no_elements(child_node);
}
}
}
} else { // no children...
if (parent.nodeType == 1) {
if ((parent.nodeName != 'BR') && (parent.nodeName != 'DIV')) {
parent.parentNode.removeChild(parent);
}
}
}
}

function move_element_up_dom(parent, child) {
var clone = child.cloneNode(true);
parent.parentNode.insertBefore(clone, parent);
if (! child.hasChildNodes()) { parent.removeChild(child); }
}

subexpression

7:38 pm on May 29, 2010 (gmt 0)

10+ Year Member



Nice work Mark! :)