Jquery contents () returns node text for each character in IE

I implement a parser that searches for text nodes matching patterns at the top level of content suitable for the content. My current code is:

//$this is the jQuery object of the contenteditable div $this.keydown(function(event){ //space bar or enter key if(event.keyCode == 32 || event.keyCode == 13){ // see how many nodes there are in the div alert($this.contents().length); $this.contents().each(function(){ //check if it is a text node if(this.nodeType == 3){ //echo if it is a text node alert(this.data); } }); }); 

With the contents of "Check it out", firefox and chrome output something like the following:

"1" (first warning)
"check it" (second warning)

So far, IE8 displays the following:
12 (first warning)
and then 12 warnings, one for each character.

Anyhoo, what I would like to do is get all the characters in a separate node text in IE. Any ideas?

+4
source share
1 answer

To do this, there is a DOM method: normalize() (see also MDC ). You need to call it on the ancestor of the text nodes that you want to normalize, for example, their parent. normalize() works in the entire subtree of the node for which it is being called, so you can call it outside of the each() loop.

 $this[0].normalize(); 

However, this method causes the entire browser to crash in some cases in IE 6 and, possibly, in later versions of IE. You may need to write your own. Here is my implementation:

 function normalize(node) { var child = node.firstChild, nextChild; while (child) { if (child.nodeType == 3) { while ((nextChild = child.nextSibling) && nextChild.nodeType == 3) { child.appendData(nextChild.data); node.removeChild(nextChild); } } else { normalize(child); } child = child.nextSibling; } } 
+4
source

All Articles