5
1

More than 1 year has passed since last update.

【Alpine.js】DOMを取得する特殊なプロパティ($el、$refs)

Last updated at Posted at 2022-12-12

DOM要素取得のためのプロパティ

①$el

これは$elを付けた要素自身を取得します。

使い方

 <button @click="$el.innerHTML = 'Hello World!'">Replace me with "Hello World!"</button>

 ↑ この$elはbutton要素自身を取得している。

$el.innnerHTML は「Replace me with "Hello World!"」を指していることになる。
(上記コードではボタンをクリックすることで「Replace me with "Hello World!"」を「Hello World」で上書きをする。)

②$refs

使い方

これはx-refと一緒に使います。

x-ref="hogehoge" ←取得したい要素に付ける

$refs.hogehoge ←これで要素を取り出せる

取得後の扱い方(el,refs共通)
JavaScriptの「getElementById」でDOM要素を取得したのと同じと考えると良いです。

例1)クラス名を扱う場合
$refs.hogehoge.classList = "クラス名 クラス名 ..."

例2)要素を取り除くとき
$refs.hogehoge.remove()

例1のコード例

See the Pen Untitled by gorimatyan (@gorimatyan) on CodePen.

まとめ

これが使えればDOMの取得がお茶の子さいさいチョチョイのチョイってワケ。

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