16
12

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.

Riot.jsでjQueryライクにDOM操作する

Last updated at Posted at 2016-07-17

Riot.jsでも、jQueryライクに$()とかで、簡単にDOM操作できないのかなと思って調べてみました。

環境は Riot.js 2.5.0

Riot.js本体のコードはどうやら短いらしいので、直接読んでみると、$()と$$()の定義を発見。

lib/browser/tag/util.js のL.376行目くらいに以下のような記述があります。

util.js
/**
 * Shorter and fast way to select multiple nodes in the DOM
 * @param   { String } selector - DOM selector
 * @param   { Object } ctx - DOM node where the targets of our search will is located
 * @returns { Object } dom nodes found
 */
function $$(selector, ctx) {
  return (ctx || document).querySelectorAll(selector)
}

/**
 * Shorter and fast way to select a single node in the DOM
 * @param   { String } selector - unique dom selector
 * @param   { Object } ctx - DOM node where the target of our search will is located
 * @returns { Object } dom node found
 */
function $(selector, ctx) {
  return (ctx || document).querySelector(selector)
}

第二引数は通常のブラウザであれば、何も入れなくて平気かと思います。

ちなみに以下のファイルでimportされているので、すぐに使えるはずです。

lib/riot.js
import 'browser/wrap/prefix'
import 'browser/global-variables'
/* istanbul ignore next */
import '../node_modules/riot-observable/dist/riot.observable.js'
/* istanbul ignore next */
import '../node_modules/riot-route/dist/riot.route.js'
/* istanbul ignore next */
import '../node_modules/riot-tmpl/dist/riot.tmpl.js'
import 'browser/tag/mkdom'
import 'browser/tag/each'
import 'browser/tag/styleManager'
import 'browser/tag/parse'
import 'browser/tag/tag'
import 'browser/tag/update'
import 'browser/tag/util'
import 'browser/index'
import 'browser/wrap/suffix'

ソースコードを読まないと気づけなかったのですが、
$()はdocument.querySelector()
$$()はdocumet.querySelectorAll()
なので注意が必要でした。

16
12
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
16
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?