5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

contenteditable でキャレットを先頭と末尾に移動させる

Posted at

contenteditable でキャレットを先頭と最後に移動させる方法

キャレットを先頭に移動

const target = document.getElementById('example')
const node = target.childNodes[0]
const editorRange = document.createRange()
const editorSel = window.getSelection()
editorRange.setStart(node, 0)
editorRange.collapse(true)
editorSel.removeAllRanges()
editorSel.addRange(editorRange)

キャレットを末尾に移動

const target = document.getElementById('example')
const p = target.childNodes[target.childNodes.length - 1]
const node = p.childNodes[p.childNodes.length - 1]
const editorRange = document.createRange()
const editorSel = window.getSelection()
editorRange.setStart(node, node.childNodes.length ? node.childNodes.length : node.length)
editorRange.collapse(true)
editorSel.removeAllRanges()
editorSel.addRange(editorRange)
5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?