Rangy (JS / jQuery) split node

How would I split the node / element in position (selection).

Example: I have this markup:

<p>This is <a href="">a te|st</a>, you like?</p> 

(this pipe represents position / choice)

I want to convert it to:

 <p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p> 

Maintaining a Choice.

Any ideas?

I and using the Rangy library as well as jQuery, but you can use raw JS if necessary.

+6
source share
1 answer

You can do this by creating a range that extends from the caret to the point immediately after the paragraph and using the extractContents() method.

Live demo: http://jsfiddle.net/timdown/rr9qs/2/

the code:

 var sel = rangy.getSelection(); if (sel.rangeCount > 0) { // Create a copy of the selection range to work with var range = sel.getRangeAt(0).cloneRange(); // Get the containing paragraph var p = range.commonAncestorContainer; while (p && (p.nodeType != 1 || p.tagName != "P") ) { p = p.parentNode; } if (p) { // Place the end of the range after the paragraph range.setEndAfter(p); // Extract the contents of the paragraph after the caret into a fragment var contentAfterRangeStart = range.extractContents(); // Collapse the range immediately after the paragraph range.collapseAfter(p); // Insert the content range.insertNode(contentAfterRangeStart); // Move the caret to the insertion point range.collapseAfter(p); sel.setSingleRange(range); } } 
+10
source

Source: https://habr.com/ru/post/918524/


All Articles