4
3

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.

javascript基礎構文(document.getElementByIdとdocument.getElementsByClassName)

Last updated at Posted at 2019-10-22

##趣旨
javascript基礎構文をまとめます。
今回はdocument.write()とdocument.getElementById()とdocument.getElementsByClassName()です。

###document.write(引数)
引数に指定した文字列を書き出すことができる

javascript
document.write("hello")

helloが表示される

表示
hello

###document.getElementById()

document.getElementById()でIDを指定し、innerHTMLでIDを指定した要素の内容を変更する

javascript
<div id ="get">messageBefore</div>

<script>
var def = document.getElementById("get");
def.innerHTML = "messageChanged";
</script>

innerHTMLで変更したmessageChangedが表示される

表示
messageChanged

###document.getElementsByClassName()

document.getElementsByClassName()でclassを指定すると配列のようなオブジェクトを返す。
for文は(初期化値; 条件式; 増加分){命令文}で繰り返し処理が走るので、for文で配列の中身を取り出すことができる。
.lengthで配列の長さをカウントしその長さの分だけ繰り返す。
今回はinnerHTMLで配列の番号を指定し、その要素の内容を変更する。

javascript
<div class ="get">messageBefore</div>

<script>
var def = document.getElementsByClassName("get");
for (var i = 0; i < def.length; i++) {
  def[i].innerHTML = "messageChanged"
}
</script>
表示
messageChanged
4
3
1

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?