To set the carriage after a specific item, you want to create a range and apply that range to the browser selection object, as shown below:
//get the browser selection object - it may or may not have a selected range var selectionn = rangy.getSelection(); //create a range object to set the caret positioning for var range = rangy.createRange(); //get the node of the element you wish to put the caret after var startNode = document.getElementById('YourTagID'); //set the caret after the node for this range range.setStartAfter(startNode); range.setEndAfter(startNode); //apply this range to the selection object selection.removeAllRanges(); selection.addRange(range);
At some point, if you want to move the caret, you would do the same as above to move it after the "DIV", although if you want the selection range to go from your tag "A" to after your tag "DIV", you will do the following:
//get the browser selection object - it may or may not have a selected range var selectionn = rangy.getSelection(); //create a range object to set the caret positioning for var range = rangy.createRange(); //get the nodes of the elements you wish to put the range between var startNode = document.getElementById('YourTagID'); var endNode = document.getElementById('YourDivTagID'); //set the caret after the node for this range range.setStartAfter(startNode); range.setEndAfter(endNode); //apply this range to the selection object selection.removeAllRanges(); selection.addRange(range);
If you want your selection to be at the end of the element, but inside the element, and not after the element, you would do something like this.
//get the browser selection object - it may or may not have a selected range var selectionn = rangy.getSelection(); //create a range object to set the caret positioning for var range = rangy.createRange(); //get the nodes of the elements you wish to put the range between var startNode = document.getElementById('YourTagID'); var endNode = document.getElementById('YourDivTagID'); //set the caret after the start node and at the end of the end node //Note: the end is set using endNode.length when the node is of the text type //and it is set using childNodes.length when the end node is of the element type range.setStartAfter(startNode); range.setEnd(endNode, endNode.length || endNode.childNodes.length); //apply this range to the selection object selection.removeAllRanges(); selection.addRange(range);
A few important notes:
- You do not need to get the start or end nodes by identifier, but you also need to get Node objects from the DOM.
- If you change the DOM, you can destroy range objects in the process. This is why the second block of code does the work of creating the range first, and not just refers to the existing range.
James source share