LoginSignup
1
0

More than 5 years have passed since last update.

自身の TextNode が親から見て何番目の Node なのかを知る方法

Posted at
<p>テキスト1<strong>強調1</strong>テキスト2</p>

こんな HTML があった時、node の構造としては以下のようになっています。

domtree.png

この時、テキスト2 となっている TextNode が p から見たときに何番目の Node なのを知りたくなったので、こんな感じのコードを書きました。取得したいのは3番目の Node ということです(0 始まりなのでコード的には 2)。

const sel = window.getSelection()
const range = sel.getRangeAt(0)
let targetNode = range.startContainer
let i = 0
while ((targetNode = targetNode.previousSibling) !== null) {
  i++
}

単に previousSibling で前の node を存在するまで見ていくだけ。

1
0
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
1
0