10
8

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.

HTMLElementの中でScriptタグを追加し、実行する

Posted at

まず、以下の例を見てみます。

<html>
  <body onload="document.getElementById('loader').innerHTML       = '<script>alert(\'hi\')<\/script>'">
   <div id="loader"></div>
  </body>
</html>

DIVの中でScriptタグを追加し、実行しますが、動きません。
この記事はDIVの中でScriptタグを使える方法を説明します。

1。innerHTMLを使えない

上記の例の動かない原因はinnerHTML でDIVのHTMLコンテンツが新HTMLStringを変わります。しかし、**<script>タグはHTMLコンテンツではないで、DOM Elementです。それで、 使うために、<script>HTMLStringDOM Elementを変更することが必要です。

2。Jqueryを使う

HTMLStringはDOM Elementを変更することに対して、Jqueryを使うことは一番簡単な方ほだと思います。

<html>
  <script src="https://code.jquery.com/jquery-     2.2.2.min.js"></script>
  <body onload="$('#loader').html('<script>alert(\'hi\') <\/script>')">
   <div id="loader"></div>
  </body>
</html>

****append, replaceWith, appendChild,...****も使えます。

3。JavaScriptを使う

他のJavaScriptも使えます。

var script=document.createElement('script');
script.innerHTML = "alert('ok')"
var div=document.getElementById('test');
div.appendChild(script)
10
8
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
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?