JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="textarea"><h1>Heading</h1>
Some sample text.
<img src="" alt=""><h2>Test</h2>
More text
<img src="" alt="">
</textarea>
<br>
<a onclick="nextAlt($('#textarea'));">Next</a>
CSS
textarea {
width: 400px;
height: 200px;
}
JavaScript
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
function nextAlt(input) {
var current = input.getCursorPosition();
var search = input.val().substr( ( 0 == current ? 0 : current + 1 ) );
var pos = current + search.search(/<[a-zA-Z]+(>|.*?[^?]>)/) + 1;
if (-1 == pos) {
alert("No elements found");
} else {
setCaretToPos(input.get(0), pos);
}
}