1

contenteditableを指定したdivの中にある文字列を選択状態にして、見出しボタンを押したときに見出しタグで挟んだ文字列を返すという処理をしたいです。

buttonが押されたときにselectionオブジェクトを取得してしまうと、buttonを押した時点の状態が取得されてしまうので、.text_bodyでmouseupされたときだけグローバル変数のselectionにselectionオブジェクトを入れて、buttonが押されたときにselectionを利用する形にすればいけると思ったのですが、ダメでした。

どうすれば.text_bodyで選択した状態のselectionオブジェクトを取得できるでしょうか。よろしくお願いいたします。

var selection = null;
document.querySelector('.text_body').addEventListener('mouseup', function(){
  selection = window.getSelection();
} )
document.querySelector('button').addEventListener('click', function(){
  document.querySelector('.result').textContent = selection.rangeCount + ', ' + selection.isCollapsed;
})
.text_body {
  width : 300px;
  height : 60px;
  border : 1px solid black;
}
<div class="text_body" contenteditable>JavaScrip Ruby PHP</div>
<button type='button'>見出し</button>
<div class="result"></div>

5
  • "文字列を選択状態" にするとは次のようなこと言っていますか? javascript.programmer-reference.com/… 2020年8月21日 11:33
  • ありがとうございます。はい、ですが、マウスで選択状態にしてボタンを押すところまではユーザーがやることで、選択された文字列をタグで囲む処理をプログラムでやりたいです。
    – bafcom
    2020年8月21日 11:48
  • タイトルを "ユーザーが選択している文字列を取得したい、ただし特定のdivタグ内のものに限る" といったニュアンスのものに変えませんか? スタックオーバーフローは、あとから来た他のエンジニアにも役立つサイトを目指していますので、わかりやすいタイトルにしたほうがよいと考えます。 2020年8月26日 6:04
  • ありがとうございます。変更しました。
    – bafcom
    2020年8月26日 22:05
  • 変更ありがとうございます 2020年8月26日 23:57

1 件の回答 1

1

どうすれば.text_bodyで選択した状態のselectionオブジェクトを取得できるでしょうか。よろしくお願いいたします。

IDによる制御

ここでは、ユーザーの選択した文字列を取得するために、window.getSelection()を使用しています。window.getSelection()をそのまま使うとユーザーが選択した箇所であればどこでも取得できてしまうため、特定のdivといったように取得箇所を限定したいのであれば、なにかしらの仕組みで特定div以外の場合は反応しないようにしなければなりません。

クラスではなくIDになってしまいますが、IDだと下記の方法でできました。
参考資料: javascript - How to getSelection() within a specific div? - Stack Overflow回答

<html>
<head>
<script>
function hoge(){
  if(window.getSelection().baseNode.parentNode.id != "foo") return;
  alert(window.getSelection());
}
</script>
</head>
<body>
  aaaa
  <div id="foo">JavaScrip Ruby PHP</div>
  <button type='button' onclick="hoge()">見出し</button>
  <div class="result"></div>
</body>
</html>

ちなみに

ちょっと遭遇していないので、どういう現象かわかってないですが
javascript - How to getSelection() within a specific div? - Stack Overflow回答
のコメント部にある

You may have to recursively check the parentNode until you reach the body as the contenteditable will create multiple tags in different hierarchy.

@z0mBi3 Good point, since this is just a "highlight once" thing it would work. I'd advise OP to use jQuery's .closest() function. I'll mention that in a edit.

も気にしたほうがいいかもしれません。このコメントを受けて回答にjQueryによる解法が付け加えられています。そのif文を書き換えた方法は下記のようです。

引用:

if($(window.getSelection().baseNode).closest("#foo").attr("id") != "foo") return;

テキストエリアの場合

特定のテキストエリア(selectionStartselectionEndが使える要素と言ったほうがいいかもしれない)でよいなら下記の方法もありました。テキストエリアであれば、window.getSelection()を使わないですみます。

javascript - HTML5 how to get selected text out of a textarea - Stack Overflow回答

念のためにテキストエリア版で重要そうなところを引用しておきます。

var textarea = document.getElementById("textArea");  
var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
alert (selection);

追記: contenteditableの場合

contenteditableですが、質問者さんは、<div class="text_body" contenteditable>と書かれていますが、trueもしくはfalseを与える必要があると思います(もしくは私が知らないだけで省略可能?)下記のように textareaと同様にいけるかと思い試してみたが、クロームで試してみたところ駄目でした
jquery - selectionStart and selectionEnd in contenteditable element - Stack Overflowcontenteditable を使った質問がありましたが、getSelectionの回答しか載っておらず、特別によさそうな方法がありませんでした

駄目だった例:

<html>
<head>
<script>
function hoge(){
  var contenteditableAria = document.getElementById("foo");  
  var selection = (contenteditableAria.value).substring(contenteditableAria.selectionStart,contenteditableAria.selectionEnd);
  alert (selection);
}
</script>
</head>
<body>
  <div id="foo" contenteditable="true">JavaScrip Ruby PHP</div>
  <button type='button' onclick="hoge()">見出し</button>
  <div class="result"></div>
</body>
</html>
0

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。