UPDATE 2
Due to OP's question changes, I will address this one last time.
P.S: I need this because I want to remove some attributes in my html on undo.
Undo Retrieves deleted text
Delete Removes text
If you have a ton of attributes in your html, use the text editor's replace feature. What text editor do you use?
UPDATE 1
Added a new function getUndone()
. Do the following to test it:
- Delete some text.
- click the ⤺ button.
- click the Get button.
- The undone portion of text will be back as expected.
- The undone text is also stored in a variable (i.e.
sel
).
- The undone text is also in clipboard.
The undone text is displayed as well.
Used execCommand('undo')
to undo.
- Used
execCommand('copy')
to store in clipboard.
- Used
window.getSelection()
to retrieve selected text and store in sel
.
- Used
.toString()
to display undone text.
execCommand
API is made for creating text editors. It has a ton of methods and properties. The following Snippet has bold, italics, underline
, and undo
.
document.execCommand( 'undo',false,null);
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<style>
body {
font: 400 16px/1.4'serif';
}
#editor1 {
border: 3px inset grey;
height: 100px;
width: 381px;
margin: 10px auto 0;
}
fieldset {
margin: 2px auto 15px;
width: 358px;
}
button {
width: 5ex;
text-align: center;
padding: 1px 3px;
}
</style>
</head>
<body>
<div id="editor1" contenteditable="true">
The quick brown fox jumped over the lazy dog.
</div>
<fieldset>
<button class="fontStyle" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"><i>I</i>
</button>
<button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
</button>
<button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
</button>
<button class="fontStyle" onclick="document.execCommand( 'undo',false,null);"><b>⤺</b>
</button>
<button class="fontStyle" onclick="getUndone()">Get</button>
<br/>
<label for='data'>Data:
<input id="data">
</label>
</fieldset>
<script>
function getUndone() {
var data = document.getElementById('data');
var sel = window.getSelection();
document.execCommand('undo', false, null);
document.execCommand('copy', false, null);
data.value = sel.toString();
}
</script>