1
0

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 3 years have passed since last update.

codepenのscriptタグでつまづいたこと

Last updated at Posted at 2020-03-13

##概要
codepenはiframeで別のブラウザでレンダリングした画面を埋め込んでいるため、手元で動かしているブラウザと異なる挙動を示す場合がある。
以下のようにjavascript内でDOMを操作する場合、htmlファイル内でのjavascriptの呼び出し( <script src="script.js"></script>)は対象のDOM(<button>)の後に書く、あるいはdeferを使用するが、codepenだと<button>の前に書いても問題なく実行出来た。

##やりたいこと
ボタンを押すと文字列が出力される、という挙動をhtmlとjavascriptで確認する。
【参照】
https://developer.mozilla.org/ja/docs/Learn/JavaScript/First_steps/What_is_JavaScript#How_do_you_add_JavaScript_to_your_page

例)codepenの場合

index.html
 <!DOCTYPE html>
 <html lang="en-US">
   <head>
     <meta charset="utf-8">
     <title>Apply JavaScript example</title>
     <script src="script.js"></script>
   </head>
   <body>
     <button onclick="">Click me</button>
   </body>
 </html>
script.js

 function createParagraph() {
   let para = document.createElement('p');
   para.textContent = 'You clicked the button!';
   document.body.appendChild(para);
 }
 
 const buttons = document.querySelectorAll('button');
 
 for(let i = 0; i < buttons.length ; i++) {
   buttons[i].addEventListener('click', createParagraph);
 }

例)手元のブラウザの場合(今回はChrome)

index.html
 <!DOCTYPE html>
 <html lang="en-US">
   <head>
     <meta charset="utf-8">
     <title>Apply JavaScript example</title>
   </head>
   <body>
     <button>Click me</button>
   </body>
   <script src="script.js"></script>
 </html> 

または

index.html
 <!DOCTYPE html>
 <html lang="en-US">
   <head>
     <meta charset="utf-8">
     <title>Apply JavaScript example</title>
     <script src="script.js" defer></script>
   </head>
   <body>
     <button>Click me</button>
   </body>
 </html> 
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?