You are so close! When you add a Document Fragment to a temporary span , you turned them into a managed group, accessible through an array.
var selnodes = tempspan.childNodes;
In addition, you are setting yourself up for some problems with this for(i in selnodes) , which returns the elements in the array, the PLUS property length and the __proto__ property, and any other properties that the object may have.
You should use only those types of for loops when navigating through object properties, and then always with if (obj.hasOwnProperty[i]) to filter properties inherited from the prototype.
When navigating through arrays, use:
for(var i=0,u=selnodes.length;i<u;i++)
Finally, once you load this array, you really need to check each element to see if it is a DOM node or a Text node before you can process it. We can do this by checking to see if it supports the tagName property.
if (typeof selnodes[i].tagName !== 'undefined')
Everybody is here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> function getSelectedNodes(){ var sel = window.getSelection(); try{var frag=sel.getRangeAt(0).cloneContents()}catch(e){return(false);} var tempspan = document.createElement("span"); tempspan.appendChild(frag); console.log(tempspan); window.selnodes = tempspan.childNodes; var output = '' for(var i=0, u=selnodes.length;i<u;i++){ if (typeof selnodes[i].tagName !== 'undefined'){ output += "A "+selnodes[i].tagName+" was found\n" } else output += "Some text was found: '"+selnodes[i].textContent+"'\n"; </script> </head> <body contentEditable="true" onkeypress="return(keypress(event))"> <div>This <strong>div</strong> is <em>content</em> <span class='red'>editable</span> and has a couple of <em><strong>child nodes</strong></em> within it</div> <br /> <br /> <a href="#" onmouseover="alert(getSelectedNodes())">hover here</a> </body> </html>
Daniel Mendel
source share