LoginSignup
1
0

More than 3 years have passed since last update.

【初心者向け】Chrome Developer Tools の Console でのJavaScript実行

Posted at

Chrome Developer Tools の Console パネルでは JavaScript が実行できる(varfunctionを定義するとundifinedと返ってきたので定義できてないのかと思ったら、そうではなかった)。

練習


function add(a, b=20) {
  return a + b;
}
// undifined と返ってくる

add(25);
// 45

検索窓フォームの値を変更してみる

スクリーンショット 2020-06-17 12.25.30.png

より実践に近い練習のために検索フォームの値を変更するコードを書きたいときに、Consoleを使って確かめながら開発するケースを想定する。

先に結論から言うと以下のコードで書き換えができる。


var parent = document.getElementsByClassName('search-form');
// undefined
parent[0].getElementsByClassName('search-field')[0].value = 'bbb';
// "bbb"

ただ上記のコードをに辿り着くまでには、Consoleで以下のようなお試しを行っている。
スクリーンショット 2020-06-17 12.21.24.png

実行したコードを1行ずつ見ていく。


var parent = document.getElementsByClassName('search-form');
// undefined ← これは今まで未定義だったという意味っぽい

parent
// HTMLCollection [form.search-form] ←ちゃんと変数に値が入っている
// 0: form.search-formlength: 
// 1__proto__: HTMLCollection

parent.children
// undefined ← よくみるとparentはCollectionなのでundefinedとなる

parent[0].children
// HTMLCollection(2) [label.screen-reader-text, input.search-field, s: input.search-field]

parent[0].getElementsByClassName('search-field');
// HTMLCollection [input.search-field, s: input.search-field]

parent[0].getElementsByClassName('search-field')[0].value = 'bbb';
// "bbb"

これで導き出したコード(プログラム)を本ちゃんのファイルに記述する。普段ChromeのConsoleによる操作をしてこなかったので、もっと良い試し方やデバッグ方法があれば教えてほしいです。

公式ドキュメントでちゃんと学んだほうがいい

Chrome DevTools で JavaScript をデバッグする
https://developers.google.com/web/tools/chrome-devtools/javascript?hl=ja

Consoleの使用
https://developers.google.com/web/tools/chrome-devtools/console/javascript?hl=ja

参考

脱jQuery
https://wemo.tech/2101

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