How to use jQuery prevAll () to select the nearest text nodes?

I get the text node (node.nodeType == 3) returned from the getSelection range, for example:

var selectionRange = selection.getRangeAt(0); var startContainer = selectionRange.startContainer; 

This startContainer is usually node text, like the following html:

 <p>Paragraph in <u>parag</u>raph.</p> 

The text node appears with the text "raph". if | indicates a choice:

 <p>Paragraph in <u>parag</u>r|aph|.</p> 

That's right, the selected text is aph, and the text node is raph., Because before the raph the new text node appears inside the u node.

Now when calling $(startContainer).prevAll().each(function(index, node) ... I expected this to return U (which contains the text node with parag) and another text node (which contains Paragraph in).

However, it only returns U, not the text node to the left of it.

Why is this? How to get all nodes with one level up to my startContainer, including text nodes with jQuery?

+4
source share
2 answers

In general, jQuery is manipulating DOM elements . It does not work (in most cases the .text() function is an obvious exception) it ignores text nodes, especially in the DOM Navigation family of functions.

Here is an older Stackoverflow question that can help you compile code for finding text nodes. As you can see in this question, the jQuery .contents() function includes text nodes. That way, you can do something like go to parent of your node text and get its contents that way, and then from this set of children you can “find yourself” and identify immediate neighbors, etc.

+4
source

Thanks to Pointy, who replied that he accepted, I came up with the following:

 var left = true; var leftNodes = []; var rightNodes = []; $(startContainer).parent().contents().each(function(index, node) { if (!left) { //right rightNodes.push(node); } else if ((node.isSameNode(startContainer)) && (left)) { left = false; } else { //left leftNodes.push(node); } }); 
+6
source

All Articles