LoginSignup
2
2

More than 5 years have passed since last update.

JavaScript で対象 node すべてを選択する2つの方法

Posted at

対象の node をすべて選択するには以下の2つのやり方がある。

<div id="example">
  <p>hoge</p>
  <p>hoge</p>
</div>
const target = document.getElementById('example')
const range = document.createRange()
const sel = window.getSelection()
range.selectNodeContents(target)
sel.removeAllRanges()
sel.addRange(range)
const target = document.getElementById('example')
const range = document.createRange()
const sel = window.getSelection()
range.setStart(target.childNodes[0], 0)
const endNode = target.childNodes[target.childNodes.length - 1]
range.setEnd(endNode, endNode.childNodes.length)
sel.removeAllRanges()
sel.addRange(range)

それぞれ同じように対象の node をすべて選択できるが、range オブジェクトが微妙に異なる。前者の selectNodeContents で対象 node を入れた場合は startContainer / endContainer / commonAncestorContainer が自身の node になる。つまり対象 node 自身を含んで選択していることになる。

後者の setStartsetEnd で指定している場合は、commonAncestorContainer は自身の node だが、startContainer / endContainer はそれぞれ setStartsetEnd で指定した node になる。これはユーザが手動で文字列を選択したときと同じような range オブジェクトになる。

どちらが良いというよりかは、それぞれ場合によって使い分ける。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2