DOM - Javascript

DOM とは?

DOM ( Document Object Model )は、Javascript などのプログラムから HTML の要素を操作する API です。

API とは、「 アプリケーション・プログラミング・インターフェース(Application Programming Interface) 」の略称で、プログラムや Web サービスの間をつなぐ「 インターフェース 」のことを指します。

インターフェースとは、コンピュータで、異なる機器・装置のあいだを接続して、交信や制御を可能にする装置やソフトウェアのことです。

DOM ツリー

Web ページの内容は、Web ブラウザが HTML ファイルを読み込むと、レンダリングエンジンによって HTML ファイルが解析されます。

解析された内容は、Document オブジェクトの中に、文書の内容を表す DOM ツリーと呼ばれるオブジェクトのツリー構造が作成されます。

DOM ツリーの一つ一つのオブジェクトを「 ノード( Node ) 」といいます。

Javascript で HTML要素を操作するには、要素オブジェクトを取得する必要があります。Document オブジェクトには、要素オブジェクトを取得するメソッドが用意されています。

id 名でノードを取得

以下の「 index.html 」というファイルをブラウザで開くと「 Hello, World 」と表示されます。

HTML - index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <h1 id="target"></h1>
</body>
</html>

Javascript - script.js

window.onload = function(){
  let target = document.getElementById("target");
  target.innerText = "Hello, World";
};

「 index.html 」のh1タグに「 target 」という id を指定しています。

Javascript では、「 target 」というid名の要素を取得し、h1要素に文字を入力しています。

class 名でノードを取得

getElementsByClassNameメソッドを使うと、指定したclass名のノードをまとめて取得できます。

以下の、「 index.html 」ファイルをブラウザで開くと「 Hello, World 」が1つだけ表示されます。

HTML - index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <h1 class="target"></h1>
  <h1 class="target"></h1>
</body>
</html>

Javascript - script.js

window.onload = function(){
  let target = document.getElementsByClassName("target");
  target[0].innerText = "Hello, World";
};

getElementsByClassName で取得したノードは、「 target[0] 」のように要素の番号を指定して操作します。

getElementsByClassName で取得したノードは、「 HTMLCollection オブジェクト 」というオブジェクトになり、配列のようなオブジェクトです。

すべての「 taget 」をまとめて操作したい場合、「 HTMLCollection オブジェクト 」は配列でないため、forEach は利用できません。

forEach を使う場合は、「 Array.from() メソッド 」を使い、配列に変更してかforEach で処理します。

「 script.js 」を以下のように変更すると、「 Hello, World 」が2つ表示されます。

Javascript - script.js

window.onload = function(){
  let target = document.getElementsByClassName("target");
  Array.from(target).forEach(function(t){
    t.innerHTML = "Hello, World";
  });
};

要素名でノードを取得

getElementsByTagName の戻り値は、「 HTMLCollection オブジェクト 」です。

li 要素のテキストがすべて「 Hello, World 」に置き換わります

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <ul>
    <li>List 1</li>
    <li>List 2</li>
    <li>List 3</li>
  </ul>
</body>
</html>

script.js

window.onload = function(){
  let li = document.getElementsByTagName("li");
  Array.from(li).forEach(function(i){
    i.innerText = "Hello, World";
  });
};

name 属性の値でノードを取得

getElementsByName の戻り値は、「 HTMLCollection オブジェクト 」です。

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <ul>
    <li name="list">List 1</li>
    <li name="list">List 2</li>
    <li name="list">List 3</li>
  </ul>
</body>
</html>

script.js

window.onload = function(){
  let list = document.getElementsByName("list");
  let lis = Array.from(list);
  lis.forEach(function(li){
      console.log(li.textContent);
  });
};

CSS セレクタによるノードの取得

「 querySelector 」は、指定した条件に一致した最初の Element を取得します。

「 querySelectorAll 」は、指定した条件に一致したすべての Element を NodeList オブジェクトで取得します。

document.querySelectorAll("セレクタ");

li要素のテキストをすべて「 Hello, World 」に変更してみます。

querySelectorAll を使い、classの属性値(target)に一致するすべてを処理する場合は、以下のようになります。

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <ul>
    <li class="list">List1</li>
    <li class="list">List2</li>
    <li class="list">List3</li>
  </ul>
</body>
</html>

script.js

window.onload = function(){
  let list = document.querySelectorAll(".list");
  let lis = Array.from(list);
  lis.forEach(function(li){
      li.innerText = "Hello,World";
  });
};

html 要素の取得

document.getElementsByTagName('html') // HTMLCollection
document.documentElement

HTML 要素にアクセスして、背景色を変更するには次のようにします。

const ht = document.getElementsByTagName('html');
ht[0].style.backgroundColor = "red";

body 要素の取得

document.getElementsByTagName('body'); // HTMLCollection
document.body;
const body = document.getElementsByTagName('body');
body[0].style.backgroundColor = "red";