Range.toString()不返回HTML标签,如何获取含标签的光标前内容?
Got it, I know exactly what you're dealing with—using Range.toString() strips out all HTML tags like <br>, which isn't helpful when you need the full formatted content up to the cursor. Here's a solid fix that preserves all the HTML structure:
Step-by-Step Explanation
Instead of relying on toString(), we'll create a range that spans from the start of your contenteditable div to the cursor position, clone those contents, and then extract the HTML from the cloned fragment. This way, we don't modify the original content and get all the tags intact.
Working Code Example
<div id="divTxt" contenteditable>Hello, I am John<br>Nice to meet you</div> <button onclick="getHtmlPrecedingCaret(document.getElementById('divTxt'))">Click</button> <script> function getHtmlPrecedingCaret(element) { // Get the current selection and range const selection = window.getSelection(); if (selection.rangeCount === 0) return ''; // No selection/caret const originalRange = selection.getRangeAt(0); // Create a new range starting at the beginning of the element, ending at the cursor const rangeToClone = document.createRange(); rangeToClone.selectNodeContents(element); rangeToClone.setEnd(originalRange.endContainer, originalRange.endOffset); // Clone the contents so we don't alter the original div const clonedContent = rangeToClone.cloneContents(); // Create a temporary container to hold the cloned content const tempContainer = document.createElement('div'); tempContainer.appendChild(clonedContent); // Get the full HTML from the temp container const htmlContent = tempContainer.innerHTML; console.log(htmlContent); return htmlContent; } </script>
How It Works
- Selection & Range Handling: We first grab the current selection (which includes the cursor position). If there's no selection, we return an empty string.
- Range Setup: We create a new range that starts at the very beginning of your contenteditable div and ends exactly where the cursor is.
- Clone Contents: Using
cloneContents()ensures we copy the content without removing it from the original div. - Temp Container: By appending the cloned fragment to a temporary div, we can easily get its
innerHTML—which includes all the HTML tags like<br>,<p>, or any other formatting present.
Testing It Out
If you place your cursor right after "John", clicking the button will return:
Hello, I am John<br>
And if you place it at the end of the text, you'll get the full HTML content of the div.
内容的提问来源于stack exchange,提问作者KANAYO AUGUSTIN UG

