<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="xBtn" style="font-size:20px">テキストをJSで挿入</button><br>
<p>
普通に書き換え<br>
<textarea id="xT1"></textarea>
</p>
<p>
execCommand('insertText')<br>
<textarea id="xT2"></textarea>
</p>
<p>
execCommand('ms-beginUndoUnit')+<br>
execCommand('ms-endUndoUnit')<br>
<textarea id="xT3"></textarea>
</p>
<script src="script.js"></script>
</body>
</html>
// Code goes here
var byId = function(id){
return document.getElementById(id);
};
var btn = byId('xBtn');
var t1 = byId('xT1');
var t2 = byId('xT2');
var t3 = byId('xT3');
btn.addEventListener('click',function(){
var newText = 'hello\n';
//普通に書き換え
t1.value = t1.value += newText;
//execCommand('insertText')
t2.focus();
document.execCommand('insertText', false, newText);
//MS対応版
try {
document.execCommand('ms-beginUndoUnit');
} catch (e) {}
t3.value = t3.value += newText;
try {
document.execCommand('ms-endUndoUnit');
} catch (e) {}
});
/* Styles go here */
textarea{
min-height:80px;
}