diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
| commit | 33058f2b292b3a581333bdfb21b8f671898c5060 (patch) | |
| tree | 51c3e392513ec574331b2d3f85c394445ea803c6 /files/ja/web/api/document_object_model | |
| parent | 8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff) | |
| download | translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2 translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip | |
initial commit
Diffstat (limited to 'files/ja/web/api/document_object_model')
10 files changed, 2193 insertions, 0 deletions
diff --git a/files/ja/web/api/document_object_model/events/index.html b/files/ja/web/api/document_object_model/events/index.html new file mode 100644 index 0000000000..1d8b1974a6 --- /dev/null +++ b/files/ja/web/api/document_object_model/events/index.html @@ -0,0 +1,88 @@ +--- +title: イベントと DOM +slug: Web/API/Document_Object_Model/Events +tags: + - DOM + - Guide + - ガイド +translation_of: Web/API/Document_Object_Model/Events +--- +<div>{{DefaultAPISidebar("DOM")}}</div> + +<h2 id="Introduction" name="Introduction">はじめに</h2> + +<p>この章では DOM のイベントモデルを説明します。この <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event">Event</a> インターフェイス自身は、 DOM のノード上にイベントを登録する為のインターフェイスと同様であり、<a href="/ja/docs/Web/API/EventTarget/addEventListener">イベントリスナー</a>であるとも言えます。いくつかの長い例は、様々な Event インターフェイスがどのように他と関連するかを示します。</p> + +<p><a href="http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture">DOM レベル 3 イベントの原案</a>に、DOM を通して 3 つのフェーズから構成されるイベントフローを明確に説明した素晴らしい説明図があります。</p> + +<p>また、イベントが DOM 内をどのように伝播するかについては更に詳細なコード例、<a href="/ja/docs/DOM/DOM_Reference/Examples#Example_5.3A_Event_Propagation">例 5: イベント伝播 (propagation)</a> を参照してください。</p> + +<h2 id="DOM_event_handler_List" name="DOM_event_handler_List">イベントリスナーの登録</h2> + +<p>DOM の要素にイベントハンドラーを登録する方法は 3 つあります。</p> + +<h3 id="EventTarget.addEventListener" name="EventTarget.addEventListener">{{domxref("EventTarget.addEventListener")}}</h3> + +<pre class="brush: js notranslate">// myButton は button 要素だと仮定します +myButton.addEventListener('click', greet, false); +function greet(event){ + // print and have a look at the event object + // always print arguments in case of overlooking any other arguments + console.log('greet:', arguments) + alert('hello world') +} +</pre> + +<p>これが最近のウェブページで使われる方法です。</p> + +<div class="blockIndicator note"> +<p><strong>注:</strong> Internet Explorer 6 から 8 はこの方法をサポートせず、 {{domxref("EventTarget.attachEvent")}} という似た API を代わりにサポートします。ブラウザー間の互換性を確保するには、数多くある JavaScript ライブラリのうちの一つを使用してください。</p> +</div> + +<p>さらに詳細を知りたい場合は {{domxref("EventTarget.addEventListener")}} のリファレンスを参照してください。</p> + +<h3 id="HTML_attribute" name="HTML_attribute"><a href="/ja/docs/Web/Guide/HTML/Event_attributes">HTML 属性</a></h3> + +<pre class="brush: html notranslate"><button onclick="alert('Hello world!')"> +</pre> + +<p>HTML 属性に書かれたこの JavaScript コードには、 <code>event</code> 引数を通してイベントオブジェクトが渡されます。<a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">返値は HTML の仕様で定義された特別な方法で処理されます</a>。</p> + +<div class="blockIndicator warning"> +<p><strong>警告:</strong> この方法は避けてください。これはマークアップを増加させ、可読性を下げます。コンテンツと振る舞いが正しく分離されておらず、バグの発見が困難になります。</p> +</div> + +<h3 id="DOM_element_properties" name="DOM_element_properties">DOM 要素のプロパティ</h3> + +<pre class="brush: js notranslate">// myButton は button 要素と仮定します +myButton.onclick = function(event){alert('Hello world')} +</pre> + +<p>この関数は 1 つの <code>event</code> 引数を取るように定義できます。<a href="http://dev.w3.org/html5/spec/webappapis.html#the-event-handler-processing-algorithm">返り値は HTML の仕様で定義された特別な方法で処理されます</a>。</p> + +<p>この書き方の問題は、各要素の各イベント毎に 1 つだけしかハンドラーを設定できないことです。</p> + +<h2 id="Accessing_Event_interfaces" name="Accessing_Event_interfaces">Event インターフェイスへのアクセス</h2> + +<p>イベントハンドラーは (DOM 要素や文書、 {{domxref("window")}} オブジェクト等を含めた) 様々なオブジェクトに追加されるでしょう。イベントが発生すると、イベントオブジェクトが生成され順番にイベントリスナーが呼ばれます。</p> + +<p>{{domxref("Event")}} インターフェイスは、イベントハンドラーの内部からアクセス可能で、第 1 引数としてイベントオブジェクトを介して渡されます。以下のシンプルな例は、イベントハンドラーにどのようにイベントオブジェクトが渡され、その中でどのように使われるかを示します。</p> + +<pre class="brush: js notranslate">function print(evt) { + // evt 引数は自動的にイベントオブジェクトに割り当てられます + // console.log と alert の違いに注意してください + console.log('print:', evt) + alert(evt) +} +// どの関数も意味を持つ適切な名前を付けてください +table_el.onclick = print +</pre> + +<h2 id="Subnav">Subnav</h2> + +<ul> + <li><a href="/ja/docs/Web/API/Document_Object_Model">DOM リファレンス</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Introduction">DOM への導入</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Events">イベントと DOM</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Examples">例</a></li> +</ul> diff --git a/files/ja/web/api/document_object_model/examples/index.html b/files/ja/web/api/document_object_model/examples/index.html new file mode 100644 index 0000000000..6762b4c2d4 --- /dev/null +++ b/files/ja/web/api/document_object_model/examples/index.html @@ -0,0 +1,321 @@ +--- +title: 例 +slug: Web/API/Document_Object_Model/Examples +tags: + - DOM + - DOM Reference +translation_of: Web/API/Document_Object_Model/Examples +--- +<div> + {{ApiRef}}</div> +<p>この章では、DOM を利用したウェブと XML 開発のより長い例をいくつか紹介します。可能な限りこれらの例ではドキュメントオブジェクトを操作する上でよく用いられる API や技法や JavaScript のパターンを利用しています。</p> +<h2 id="Example_1.3A_height_and_width" name="Example_1.3A_height_and_width">例 1: 高さと幅</h2> +<p>以下では、画像の大きさを変えるにあたって、<code>height</code> と <code>width</code> プロパティを使っている例を示します。</p> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> + +<head> +<title>width/height example</title> +<script> +function init() { + var arrImages = new Array(3); + + arrImages[0] = document.getElementById("image1"); + arrImages[1] = document.getElementById("image2"); + arrImages[2] = document.getElementById("image3"); + + var objOutput = document.getElementById("output"); + var strHtml = "<ul>"; + + for (var i = 0; i < arrImages.length; i++) { + strHtml += "<li>image" + (i+1) + + ": height=" + arrImages[i].height + + ", width=" + arrImages[i].width + + ", style.height=" + arrImages[i].style.height + + ", style.width=" + arrImages[i].style.width + + "<\/li>"; + } + + strHtml += "<\/ul>"; + objOutput.innerHTML = strHtml; +} +</script> +</head> +<body onload="init();"> + +<p>Image 1: no height, width, or style + <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif"> +</p> + +<p>Image 2: height="50", width="500", but no style + <img id="image2" src="http://www.mozilla.org/images/mozilla-banner.gif" + height="50" width="500"> +</p> + +<p>Image 3: no height, width, but style="height: 50px; width: 500px;" + <img id="image3" src="http://www.mozilla.org/images/mozilla-banner.gif" + style="height: 50px; width: 500px;"> +</p> + +<div id="output"> </div> +</body> +</html> +</pre> +<p><code>height</code> と <code>width</code> は <code>OBJECT</code> と <code>APPLET</code> 要素のプロパティでもあります。</p> +<h2 id="Example_2.3A_Image_Attributes" name="Example_2.3A_Image_Attributes">例 2: イメージの属性</h2> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> + +<head> +<title>Modifying an image border</title> +<script> +function setBorderWidth(width) { + document.getElementById("img1").style.borderWidth = width + "px"; +} +</script> +</head> + +<body> +<p> + <img id="img1" src="image1.gif" style="border: 5px solid green;" width="100" + height="100" alt="border test"> +</p> + +<form name="FormName"> + <p><input type="button" value="Make border 20px-wide" + onclick="setBorderWidth(20);"> <input type="button" value="Make border 5px-wide" + onclick="setBorderWidth(5);"></p> +</form> + +</body> +</html> +</pre> +<h2 id="Example_3.3A_Manipulating_Styles" name="Example_3.3A_Manipulating_Styles">例 3: スタイルを操作する</h2> +<p>この簡単なサンプルでは、HTML のパラグラフ (p) 要素の基本的ないくつかのスタイルプロパティは、DOM から検索設定される要素のスタイルオブジェクトとそのオブジェクトの CSS スタイルプロパティを使って、アクセスされます。この場合は、個々のスタイルが直接操作されています。次の例 (例 4 を参照) では、スタイルシートとそのルールを使用して、全ドキュメントに対してスタイルを変更することができます。</p> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> + +<head> +<title>Changing color and font-size example</title> +<script> +function changeText() { + var p = document.getElementById("pid"); + p.style.color = "blue" + p.style.fontSize = "18pt" +} +</script> +</head> + +<body> + +<p id="pid" + onclick="window.location.href = 'http://www.cnn.com/';">linker</p> +<form> + +<p><input value="rec" type="button" onclick="changeText();"></p> + +</form> + +</body> +</html> +</pre> +<h2 id="Example_4.3A_Using_Stylesheets" name="Example_4.3A_Using_Stylesheets">例 4: スタイルシートを利用する</h2> +<p>document オブジェクト上の styleSheets プロパティは、その document に読み込まれたスタイルシートの一覧を返します。このページの例に示されているように、stylesheet、style、CSSRule オブジェクトを利用して、これらのスタイルシートとそのルールに個別にアクセスが可能です。そしてこの例では、すべてのスタイル・ルールのセレクタ (selector) がコンソールへ表示されます。</p> +<pre class="brush:js">var ss = document.styleSheets; + +for(var i = 0; i < ss.length; i++) { + for(var j = 0; j < ss[i].cssRules.length; j++) { + dump( ss[i].cssRules[j].selectorText + "\n" ); + } +}</pre> +<p>以下の 3 つのルールが定義される単一のスタイルシートが附属されているドキュメント用に対して:</p> +<pre class="brush:css">body { background-color: darkblue; } +p { font-face: Arial; font-size: 10pt; margin-left: .125in; } +#lumpy { display: none; } +</pre> +<p>このスクリプトは以下の項目を表示します:</p> +<pre>BODY +P +#LUMPY +</pre> +<h2 id="Example_5.3A_Event_Propagation" name="Example_5.3A_Event_Propagation">例 5: イベント伝播 (propagation)</h2> +<p>この例は DOM でイベントが発生したときの対処方法を、ごく単純化して紹介します。下記の HTML 文書の BODY が読み込まれる時、イベントリスナーが TABLE の第 1 行を使って登録されます。イベントリスナーは関数 stopEvent を実行することでイベントを処理します。この関数は、table の一番下のセルの値を変更します。</p> +<p>しかし、stopEvent はまたイベントオブジェクトのメソッド {{domxref("event.stopPropagation")}} を呼出します。このメソッドはイベントが発生してこれ以上 DOM に入り込むのを防止します。テーブル自体は、クリックされた時、メッセージを表示する必要のある {{domxref("element.onclick","onclick")}} イベントハンドラを備えています。しかし stopEvent メソッドは伝播を停止していますので、テーブル内のデータが更新された後では、イベントは効率的に終了し、これを確認するための警告ダイアログが表示されます。</p> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> +<head> +<title>Event Propagation</title> + +<style> +#t-daddy { border: 1px solid red } +#c1 { background-color: pink; } +</style> + +<script> +function stopEvent(ev) { + c2 = document.getElementById("c2"); + c2.innerHTML = "hello"; + + // this ought to keep t-daddy from getting the click. + ev.stopPropagation(); + alert("event propagation halted."); +} + +function load() { + elem = document.getElementById("tbl1"); + elem.addEventListener("click", stopEvent, false); +} +</script> +</head> + +<body onload="load();"> + +<table id="t-daddy" onclick="alert('hi');"> + <tr id="tbl1"> + <td id="c1">one</td> + </tr> + <tr> + <td id="c2">two</td> + </tr> +</table> + +</body> +</html> +</pre> +<h2 id="Example_6.3A_getComputedStyle" name="Example_6.3A_getComputedStyle">例 6: getComputedStyle</h2> +<p>この例は、要素の <code>style</code> 属性あるいは JavaScript (例: <code>elt.style.backgroundColor="rgb(173, 216, 230)"</code>) で設定されていないスタイルを取得する {{domxref("window.getComputedStyle")}} メソッドの使用方法を示します。JavaScript で設定されていないケースは、もっと直接的な <a href="/ja/docs/Web/API/element.style">elt.style</a> プロパティを使って取得可能です。そのプロパティは <a href="/ja/docs/Web/API/CSS">DOM CSS プロパティリスト</a> に一覧となっています。</p> +<p><code>getComputedStyle()</code> は <code>ComputedCSSStyleDeclaration</code> オブジェクトを返し、下記のサンプルにあるように、このオブジェクトの <code>getPropertyValue()</code> メソッドによって個々のスタイルプロパティを参照できます。</p> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> + +<head> +<title>getComputedStyle example</title> + +<script> +function cStyles() { + var RefDiv = document.getElementById("d1"); + + var txtHeight = document.getElementById("t1"); + var h_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("height"); + txtHeight.value = h_style; + + var txtWidth = document.getElementById("t2"); + var w_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("width"); + + txtWidth.value = w_style; + + var txtBackgroundColor = document.getElementById("t3"); + var b_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("background-color"); + + txtBackgroundColor.value = b_style; +} +</script> + +<style> +#d1 { margin-left: 10px; background-color: rgb(173, 216, 230); +height: 20px; max-width: 20px; } +</style> + +</head> + +<body> + +<div id="d1">&nbsp;</div> + +<form action=""> +<p><button type="button" onclick="cStyles();">getComputedStyle</button> + height<input id="t1" type="text" value="1"> + max-width<input id="t2" type="text" value="2"> + bg-color<input id="t3" type="text" value="3"></p> +</form> + +</body> +</html> +</pre> +<h2 id="Example_7.3A_Displaying_Event_Object_Properties" name="Example_7.3A_Displaying_Event_Object_Properties">例 7: イベントオブジェクトのプロパティを表示する</h2> +<p>この例では、DOM メソッドを使って、 {{domxref("window.onload")}} <a href="/ja/docs/Web/API/event">event</a> オブジェクトのプロパティとそれらの値をすべて表として表示しています。また、オブジェクトのプロパティを反復し、それらの値を取得するために、for...in ループを使った役に立つテクニックをお見せします。</p> +<p>イベントオブジェクトのプロパティはブラウザによって大きく異なります。<a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">W3C DOM 2 Events 仕様書</a> に標準のプロパティが載っていますが、多くのブラウザはこれらを大幅に拡張しています。</p> +<p>以下のコードをテキストファイルとして保存し、様々なブラウザで読み込ませてみてください。プロパティの数や名称が異なることに驚かれることでしょう。ページにいくつか要素を追加して、異なるイベントハンドラからこの関数を呼び出してみるのも良いでしょう。</p> +<pre class="brush:html"><!DOCTYPE html> +<html lang="en"> +<title>Show Event properties</title> + +<style> +table {border-collapse: collapse;} +thead {font-weight: bold;} +td {padding: 2px 10px 2px 10px;} +.odd {background-color: #efdfef;} +.even {background-color: #ffffff;} +</style> + +<script> + +function showEventProperties(e) { + function addCell(row, text) { + var cell = row.insertCell(-1); + cell.appendChild(document.createTextNode(text)); + } + + var e = e || window.event; + document.getElementById('eventType').innerHTML = e.type; + + var table = document.createElement('table'); + var thead = table.createTHead(); + var row = thead.insertRow(-1); + var lableList = ['#', 'Property', 'Value']; + var len = lableList.length; + + for (var i = 0; i < len; i++) { + addCell(row, lableList[i]); + } + + var tbody = document.createElement('tbody'); + table.appendChild(tbody); + + for (var p in e) { + row = tbody.insertRow(-1); + row.className = (row.rowIndex % 2)? 'odd':'even'; + addCell(row, row.rowIndex); + addCell(row, p); + addCell(row, e[p]); + } + + document.body.appendChild(table); +} + +window.onload = function(event){ + showEventProperties(event); +} +</script> + +<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1> +</pre> +<h2 id="Example_8.3A_Using_the_DOM_Table_Interface" name="Example_8.3A_Using_the_DOM_Table_Interface">例 8: DOM のテーブルインタフェースを使用する</h2> +<p>DOM の HTMLTableElement インタフェースによって、テーブルを生成、操作するための便利なメソッドがいくつか提供されています。よく利用される 2 つのメソッドは <code><a href="/ja/docs/Web/API/table.insertRow">table.insertRow</a></code> と <code><a href="/ja/docs/Web/API/table/row.insertCell">row.insertCell</a></code> です。</p> +<p>以下の例では、既存のテーブルに行といくつかのセルを追加しています。</p> +<pre class="brush:html"><table id="table0"> + <tr> + <td>Row 0 Cell 0</td> + <td>Row 0 Cell 1</td> + </tr> +</table> + +<script> +var table = document.getElementById('table0'); +var row = table.insertRow(-1); +var cell, + text; + +for (var i = 0; i < 2; i++) { + cell = row.insertCell(-1); + text = 'Row ' + row.rowIndex + ' Cell ' + i; + cell.appendChild(document.createTextNode(text)); +} +</script> +</pre> +<h3 id="Notes" name="Notes">注記</h3> +<ul> + <li>テーブルの {{domxref("element.innerHTML","innerHTML")}} プロパティは、テーブル全体あるいはセルの内容を記述するために使うことはできますが、テーブルを操作するために使うべきではありません。</li> + <li>DOM Core メソッドの {{domxref("document.createElement")}} と {{domxref("Node.appendChild")}} を使って行とセルを生成する場合、他のブラウザでは table 要素に直接追加できる (行は最後の tbody 要素に追加される) のに対して、IE ではそれらを tbody 要素に対して追加する必要があります。</li> + <li><a href="/ja/docs/Web/API/HTMLTableElement#Methods">table interface</a> には、この他にも、テーブルを生成したり操作するのに利用できる多くの便利なメソッドがあります。</li> +</ul> diff --git a/files/ja/web/api/document_object_model/how_to_create_a_dom_tree/index.html b/files/ja/web/api/document_object_model/how_to_create_a_dom_tree/index.html new file mode 100644 index 0000000000..4f6bc2a9cd --- /dev/null +++ b/files/ja/web/api/document_object_model/how_to_create_a_dom_tree/index.html @@ -0,0 +1,152 @@ +--- +title: DOM ツリーの作成方法 +slug: Web/API/Document_Object_Model/How_to_create_a_DOM_tree +tags: + - AJAX + - Add-ons + - DOM + - Extensions + - JXON + - XML +translation_of: Web/API/Document_object_model/How_to_create_a_DOM_tree +--- +<p>{{draft}}</p> + +<p>このページでは JavaScript において <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html">DOM Core</a> API を用いて DOM オブジェクトを作成したり変更したりする方法を解説します。これはすべての Gecko ベースアプリケーション(Firefox など)で特権付きコード(拡張機能)でも特権なしコード(ウェブページ)でも利用できます。</p> + +<h2 id="英語版章題('Dynamically_creating_a_DOM_tree')_DOM_ツリーの動的作成">{{ 英語版章題('Dynamically creating a DOM tree') }}DOM ツリーの動的作成</h2> + +<p>次の XML 文書を考えます。</p> + +<pre class="brush: xml"><?xml version="1.0"?> +<people> + <person first-name="eric" middle-initial="H" last-name="jung"> + <address street="321 south st" city="denver" state="co" country="usa"/> + <address street="123 main st" city="arlington" state="ma" country="usa"/> + </person> + + <person first-name="jed" last-name="brown"> + <address street="321 north st" city="atlanta" state="ga" country="usa"/> + <address street="123 west st" city="seattle" state="wa" country="usa"/> + <address street="321 south avenue" city="denver" state="co" country="usa"/> + </person> +</people> +</pre> + +<p>次のように W3C DOM API を使うことでこの文書のインメモリ表現を作成することができます。Mozilla はこの API をサポートしています。</p> + +<pre class="brush: js">var doc = document.implementation.createDocument("", "", null); +var peopleElem = doc.createElement("people"); + +var personElem1 = doc.createElement("person"); +personElem1.setAttribute("first-name", "eric"); +personElem1.setAttribute("middle-initial", "h"); +personElem1.setAttribute("last-name", "jung"); + +var addressElem1 = doc.createElement("address"); +addressElem1.setAttribute("street", "321 south st"); +addressElem1.setAttribute("city", "denver"); +addressElem1.setAttribute("state", "co"); +addressElem1.setAttribute("country", "usa"); +personElem1.appendChild(addressElem1); + +var addressElem2 = doc.createElement("address"); +addressElem2.setAttribute("street", "123 main st"); +addressElem2.setAttribute("city", "arlington"); +addressElem2.setAttribute("state", "ma"); +addressElem2.setAttribute("country", "usa"); +personElem1.appendChild(addressElem2); + +var personElem2 = doc.createElement("person"); +personElem2.setAttribute("first-name", "jed"); +personElem2.setAttribute("last-name", "brown"); + +var addressElem3 = doc.createElement("address"); +addressElem3.setAttribute("street", "321 north st"); +addressElem3.setAttribute("city", "atlanta"); +addressElem3.setAttribute("state", "ga"); +addressElem3.setAttribute("country", "usa"); +personElem2.appendChild(addressElem3); + +var addressElem4 = doc.createElement("address"); +addressElem4.setAttribute("street", "123 west st"); +addressElem4.setAttribute("city", "seattle"); +addressElem4.setAttribute("state", "wa"); +addressElem4.setAttribute("country", "usa"); +personElem2.appendChild(addressElem4); + +var addressElem5 = doc.createElement("address"); +addressElem5.setAttribute("street", "321 south avenue"); +addressElem5.setAttribute("city", "denver"); +addressElem5.setAttribute("state", "co"); +addressElem5.setAttribute("country", "usa"); +personElem2.appendChild(addressElem5); + +peopleElem.appendChild(personElem1); +peopleElem.appendChild(personElem2); +doc.appendChild(peopleElem); +</pre> + +<p><a href="/ja/XUL_Tutorial/Document_Object_Model" title="ja/XUL_Tutorial/Document_Object_Model">XUL チュートリアルの DOM の章</a> も参照してください。</p> + +<p>You can automate the creation of a DOM tree using a <a href="/en/JXON#JXON_reverse_algorithms" title="en/JXON#JXON_reverse_algorithms">JXON reverse algorithm</a> in association with the following JSON representation:</p> + +<pre class="brush: js">{ + "people": { + "person": [{ + "address": [{ + "@street": "321 south st", + "@city": "denver", + "@state": "co", + "@country": "usa" + }, { + "@street": "123 main st", + "@city": "arlington", + "@state": "ma", + "@country": "usa" + }], + "@first-name": "eric", + "@middle-initial": "H", + "@last-name": "jung" + }, { + "address": [{ + "@street": "321 north st", + "@city": "atlanta", + "@state": "ga", + "@country": "usa" + }, { + "@street": "123 west st", + "@city": "seattle", + "@state": "wa", + "@country": "usa" + }, { + "@street": "321 south avenue", + "@city": "denver", + "@state": "co", + "@country": "usa" + }], + "@first-name": "jed", + "@last-name": "brown" + }] + } +} +</pre> + +<h3 id="英語版章題('So_what')_つまり">{{ 英語版章題('So what?') }}つまり ?</h3> + +<p>DOM ツリーを <a href="/ja/Using_XPath" title="ja/Using_XPath"> XPath 式を用いてクエリすること</a> や、文字列に変換すること、<a href="/ja/Parsing_and_serializing_XML" title="ja/Parsing_and_serializing_XML"> XMLSerializer</a> を用いてローカルあるいはリモートのファイルに書き出すこと(あらかじめ文字列に変換する必要はない)、<a href="/ja/DOM/XMLHttpRequest" title="ja/DOM/XMLHttpRequest">ウェブサーバに POST すること</a>(<code>XMLHttpRequest</code> 経由)、<a href="/ja/XSLT" title="ja/XSLT">XSLT</a> を用いて変換すること、<a href="/ja/XLink" title="ja/XLink">XLink</a> されることなど、さまざまな利用法があります。</p> + +<p>RDF は適さない(あるいは RDF が嫌いなだけという場合でも)データを DOM ツリーを用いて作ることができます。別の応用例として、XUL は XML であるため、アプリケーションの UI を動的に操作したり、ダウンロードやアップロードをしたり、保存や読み込みをしたり、変換したりといったことがかなり簡単にできます。</p> + +<h2 id="英語版章題('See_also')_参照">{{ 英語版章題('See also') }}参照</h2> + +<ul> + <li><a class="internal" href="/ja/XML" title="ja/XML">XML</a></li> + <li><a class="internal" href="/ja/JXON" title="ja/JXON">JXON</a></li> + <li><a class="internal" href="/ja/XPath" title="ja/XPath">XPath</a></li> + <li><a class="internal" href="/ja/E4X" title="ja/E4X">E4X (ECMAScript for XML)</a></li> + <li><a class="internal" href="/ja/Parsing_and_serializing_XML" title="ja/Parsing_and_serializing_XML">Parsing and serializing XML</a></li> + <li><a class="internal" href="/ja/DOM/XMLHttpRequest" title="ja/XMLHttpRequest">XMLHttpRequest</a></li> +</ul> + +<div>{{ languages( { "en": "en/How_to_create_a_DOM_tree", "fr": "fr/Comment_cr\u00e9er_un_arbre_DOM", "zh-cn": "cn/How_to_create_a_DOM_tree"}) }}</div> diff --git a/files/ja/web/api/document_object_model/index.html b/files/ja/web/api/document_object_model/index.html new file mode 100644 index 0000000000..3c27d422aa --- /dev/null +++ b/files/ja/web/api/document_object_model/index.html @@ -0,0 +1,348 @@ +--- +title: ドキュメントオブジェクトモデル (DOM) +slug: Web/API/Document_Object_Model +tags: + - API + - DOM + - Document + - Document Object Model + - Guide + - Overview + - Reference + - Web + - ガイド + - リファレンス +translation_of: Web/API/Document_Object_Model +--- +<div>{{DefaultAPISidebar("DOM")}}</div> + +<p><span class="seoSummary"><strong>Document Object Model</strong> (<strong>DOM</strong>) は、— ウェブページを表す HTML のように — 文書の構造をメモリ内に表現することで、ウェブページとスクリプトやプログラミング言語を接続するものです。</span>ふつうは JavaScript を使用しますが、 HTML、 SVG、 XML などの文書をオブジェクトとしてモデリングすることはコア JavaScript 言語の一部ではありません。</p> + +<p>DOM のモデルは文書を論理的なツリーで表現します。ツリーのそれぞれの枝はノードで終わっており、それぞれのノードがオブジェクトを含んでいます。 DOM のメソッドでプログラム的にツリーにアクセスできます。これにより、文書構造やスタイルやコンテンツを変更することができます。</p> + +<p>ノードにはイベントハンドラーを割り当てることができます。イベントが発生すると、イベントハンドラーが実行されます。</p> + +<div class="blockIndicator note"> +<p>DOM とは何であるか、どのように文書を表現するのかについて<strong>もっと学習する</strong>のであれば、 <a href="/ja/docs/Web/API/Document_Object_Model/Introduction">DOM 入門</a>をご覧ください。</p> +</div> + +<h2 id="DOM_interfaces" name="DOM_interfaces">DOM インターフェイス</h2> + +<div class="index"> +<ul> + <li>{{DOMxRef("Attr")}}</li> + <li>{{DOMxRef("CDATASection")}}</li> + <li>{{DOMxRef("CharacterData")}}</li> + <li>{{DOMxRef("ChildNode")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("Comment")}}</li> + <li>{{DOMxRef("CustomEvent")}}</li> + <li>{{DOMxRef("Document")}}</li> + <li>{{DOMxRef("DocumentFragment")}}</li> + <li>{{DOMxRef("DocumentType")}}</li> + <li>{{DOMxRef("DOMError")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("DOMException")}}</li> + <li>{{DOMxRef("DOMImplementation")}}</li> + <li>{{DOMxRef("DOMString")}}</li> + <li>{{DOMxRef("DOMTimeStamp")}}</li> + <li>{{DOMxRef("DOMStringList")}}</li> + <li>{{DOMxRef("DOMTokenList")}}</li> + <li>{{DOMxRef("Element")}}</li> + <li>{{DOMxRef("Event")}}</li> + <li>{{DOMxRef("EventTarget")}}</li> + <li>{{DOMxRef("HTMLCollection")}}</li> + <li>{{DOMxRef("MutationObserver")}}</li> + <li>{{DOMxRef("MutationRecord")}}</li> + <li>{{DOMxRef("NamedNodeMap")}}</li> + <li>{{DOMxRef("Node")}}</li> + <li>{{DOMxRef("NodeFilter")}}</li> + <li>{{DOMxRef("NodeIterator")}}</li> + <li>{{DOMxRef("NodeList")}}</li> + <li>{{DOMxRef("NonDocumentTypeChildNode")}}</li> + <li>{{DOMxRef("ParentNode")}}</li> + <li>{{DOMxRef("ProcessingInstruction")}}</li> + <li>{{DOMxRef("Selection")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("Range")}}</li> + <li>{{DOMxRef("Text")}}</li> + <li>{{DOMxRef("TextDecoder")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("TextEncoder")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("TimeRanges")}}</li> + <li>{{DOMxRef("TreeWalker")}}</li> + <li>{{DOMxRef("URL")}}</li> + <li>{{DOMxRef("Window")}}</li> + <li>{{DOMxRef("Worker")}}</li> + <li>{{DOMxRef("XMLDocument")}} {{Experimental_Inline}}</li> +</ul> +</div> + +<h3 id="Obsolete_DOM_interfaces" name="Obsolete_DOM_interfaces">廃止された DOM インターフェイス</h3> + +<p>Document Object Model は高度に単純化されてきています。このため、 DOM レベル3以前の仕様書にあった以下のインターフェイスは削除されています。一部が再導入されるかどうかはまだあまり不明ですが、当面は廃止されたと考え、使用を避けてください。</p> + +<div class="index"> +<ul> + <li>{{DOMxRef("DocumentTouch")}}</li> + <li>{{DOMxRef("DOMConfiguration")}}</li> + <li>{{DOMxRef("DOMErrorHandler")}}</li> + <li>{{DOMxRef("DOMImplementationList")}}</li> + <li>{{DOMxRef("DOMImplementationRegistry")}}</li> + <li>{{DOMxRef("DOMImplementationSource")}}</li> + <li>{{DOMxRef("DOMLocator")}}</li> + <li>{{DOMxRef("DOMObject")}}</li> + <li>{{DOMxRef("DOMSettableTokenList")}}</li> + <li>{{DOMxRef("DOMUserData")}}</li> + <li>{{DOMxRef("ElementTraversal")}}</li> + <li>{{DOMxRef("Entity")}}</li> + <li>{{DOMxRef("EntityReference")}}</li> + <li>{{DOMxRef("NameList")}}</li> + <li>{{DOMxRef("Notation")}}</li> + <li>{{DOMxRef("TypeInfo")}}</li> + <li>{{DOMxRef("UserDataHandler")}}</li> +</ul> +</div> + +<h2 id="HTML_DOM">HTML DOM</h2> + +<p>HTML を含む文書は、 HTML 仕様で拡張した様々な HTML 固有の機能を含む {{DOMxRef("Document")}} インターフェイスを使用して記述されます。具体的には、 {{domxref("Element")}} インターフェイスは拡張されて {{domxref("HTMLElement")}} を始めとするのサブクラスになっており、それぞれが要素の一つ (または深く関係した同類のもの) を表します。</p> + +<p>HTML DOM API によって、タブやウィンドウ、 CSS スタイルやスタイルシート、ブラウザーの履歴など、様々なブラウザーの機能にアクセスすることができます。これらのインターフェイスの詳細については、 <a href="/ja/docs/Web/API/HTML_DOM">HTML DOM API</a> のドキュメントにあります。</p> + +<h2 id="SVG_interfaces" name="SVG_interfaces">SVG のインターフェイス</h2> + +<h3 id="SVG_element_interfaces" name="SVG_element_interfaces">SVG 要素のインターフェイス</h3> + +<div class="index"> +<ul> + <li>{{DOMxRef("SVGAElement")}}</li> + <li>{{DOMxRef("SVGAltGlyphElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGAltGlyphDefElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGAltGlyphItemElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGAnimationElement")}}</li> + <li>{{DOMxRef("SVGAnimateElement")}}</li> + <li>{{DOMxRef("SVGAnimateColorElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGAnimateMotionElement")}}</li> + <li>{{DOMxRef("SVGAnimateTransformElement")}}</li> + <li>{{DOMxRef("SVGCircleElement")}}</li> + <li>{{DOMxRef("SVGClipPathElement")}}</li> + <li>{{DOMxRef("SVGColorProfileElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGComponentTransferFunctionElement")}}</li> + <li>{{DOMxRef("SVGCursorElement")}}</li> + <li>{{DOMxRef("SVGDefsElement")}}</li> + <li>{{DOMxRef("SVGDescElement")}}</li> + <li>{{DOMxRef("SVGElement")}}</li> + <li>{{DOMxRef("SVGEllipseElement")}}</li> + <li>{{DOMxRef("SVGFEBlendElement")}}</li> + <li>{{DOMxRef("SVGFEColorMatrixElement")}}</li> + <li>{{DOMxRef("SVGFEComponentTransferElement")}}</li> + <li>{{DOMxRef("SVGFECompositeElement")}}</li> + <li>{{DOMxRef("SVGFEConvolveMatrixElement")}}</li> + <li>{{DOMxRef("SVGFEDiffuseLightingElement")}}</li> + <li>{{DOMxRef("SVGFEDisplacementMapElement")}}</li> + <li>{{DOMxRef("SVGFEDistantLightElement")}}</li> + <li>{{DOMxRef("SVGFEDropShadowElement")}}</li> + <li>{{DOMxRef("SVGFEFloodElement")}}</li> + <li>{{DOMxRef("SVGFEFuncAElement")}}</li> + <li>{{DOMxRef("SVGFEFuncBElement")}}</li> + <li>{{DOMxRef("SVGFEFuncGElement")}}</li> + <li>{{DOMxRef("SVGFEFuncRElement")}}</li> + <li>{{DOMxRef("SVGFEGaussianBlurElement")}}</li> + <li>{{DOMxRef("SVGFEImageElement")}}</li> + <li>{{DOMxRef("SVGFEMergeElement")}}</li> + <li>{{DOMxRef("SVGFEMergeNodeElement")}}</li> + <li>{{DOMxRef("SVGFEMorphologyElement")}}</li> + <li>{{DOMxRef("SVGFEOffsetElement")}}</li> + <li>{{DOMxRef("SVGFEPointLightElement")}}</li> + <li>{{DOMxRef("SVGFESpecularLightingElement")}}</li> + <li>{{DOMxRef("SVGFESpotLightElement")}}</li> + <li>{{DOMxRef("SVGFETileElement")}}</li> + <li>{{DOMxRef("SVGFETurbulenceElement")}}</li> + <li>{{DOMxRef("SVGFilterElement")}}</li> + <li>{{DOMxRef("SVGFilterPrimitiveStandardAttributes")}}</li> + <li>{{DOMxRef("SVGFontElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFontFaceElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFontFaceFormatElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFontFaceNameElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFontFaceSrcElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFontFaceUriElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGForeignObjectElement")}}</li> + <li>{{DOMxRef("SVGGElement")}}</li> + <li>{{DOMxRef("SVGGeometryElement")}}</li> + <li>{{DOMxRef("SVGGlyphElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGGlyphRefElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGGradientElement")}}</li> + <li>{{DOMxRef("SVGGraphicsElement")}}</li> + <li>{{DOMxRef("SVGHatchElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGHatchpathElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGHKernElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGImageElement")}}</li> + <li>{{DOMxRef("SVGLinearGradientElement")}}</li> + <li>{{DOMxRef("SVGLineElement")}}</li> + <li>{{DOMxRef("SVGMarkerElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGMaskElement")}}</li> + <li>{{DOMxRef("SVGMeshElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGMeshGradientElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGMeshpatchElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGMeshrowElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGMetadataElement")}}</li> + <li>{{DOMxRef("SVGMissingGlyphElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGMPathElement")}}</li> + <li>{{DOMxRef("SVGPathElement")}}</li> + <li>{{DOMxRef("SVGPatternElement")}}</li> + <li>{{DOMxRef("SVGPolylineElement")}}</li> + <li>{{DOMxRef("SVGPolygonElement")}}</li> + <li>{{DOMxRef("SVGRadialGradientElement")}}</li> + <li>{{DOMxRef("SVGRectElement")}}</li> + <li>{{DOMxRef("SVGScriptElement")}}</li> + <li>{{DOMxRef("SVGSetElement")}}</li> + <li>{{DOMxRef("SVGSolidcolorElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGStopElement")}}</li> + <li>{{DOMxRef("SVGStyleElement")}}</li> + <li>{{DOMxRef("SVGSVGElement")}}</li> + <li>{{DOMxRef("SVGSwitchElement")}}</li> + <li>{{DOMxRef("SVGSymbolElement")}}</li> + <li>{{DOMxRef("SVGTextContentElement")}}</li> + <li>{{DOMxRef("SVGTextElement")}}</li> + <li>{{DOMxRef("SVGTextPathElement")}}</li> + <li>{{DOMxRef("SVGTextPositioningElement")}}</li> + <li>{{DOMxRef("SVGTitleElement")}}</li> + <li>{{DOMxRef("SVGTRefElement")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGTSpanElement")}}</li> + <li>{{DOMxRef("SVGUseElement")}}</li> + <li>{{DOMxRef("SVGUnknownElement")}} {{Experimental_Inline}}</li> + <li>{{DOMxRef("SVGViewElement")}}</li> + <li>{{DOMxRef("SVGVKernElement")}} {{Deprecated_Inline}}</li> +</ul> +</div> + +<h3 id="SVG_data_type_interfaces" name="SVG_data_type_interfaces">SVG データ型のインターフェイス</h3> + +<p>SVG のプロパティと属性の定義で使用されるデータタイプの DOM API を次に示します。</p> + +<h4 id="Static_type" name="Static_type">静的型</h4> + +<div class="index"> +<ul> + <li>{{DOMxRef("SVGAngle")}}</li> + <li>{{DOMxRef("SVGColor")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGICCColor")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGElementInstance")}}</li> + <li>{{DOMxRef("SVGElementInstanceList")}}</li> + <li>{{DOMxRef("SVGLength")}}</li> + <li>{{DOMxRef("SVGLengthList")}}</li> + <li>{{DOMxRef("SVGMatrix")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGNameList")}}</li> + <li>{{DOMxRef("SVGNumber")}}</li> + <li>{{DOMxRef("SVGNumberList")}}</li> + <li>{{DOMxRef("SVGPaint")}}</li> + <li>{{DOMxRef("SVGPathSeg")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegClosePath")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegMovetoAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegMovetoRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoCubicAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoCubicRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoQuadraticAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoQuadraticRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegArcAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegArcRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoHorizontalAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoHorizontalRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoVerticalAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegLinetoVerticalRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoCubicSmoothAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoCubicSmoothRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoQuadraticSmoothAbs")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegCurvetoQuadraticSmoothRel")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPathSegList")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPoint")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPointList")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGPreserveAspectRatio")}}</li> + <li>{{DOMxRef("SVGRect")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGStringList")}}</li> + <li>{{DOMxRef("SVGTransform")}}</li> + <li>{{DOMxRef("SVGTransformList")}}</li> +</ul> +</div> + +<h4 id="Animated_type" name="Animated_type">アニメーション型</h4> + +<div class="index"> +<ul> + <li>{{DOMxRef("SVGAnimatedAngle")}}</li> + <li>{{DOMxRef("SVGAnimatedBoolean")}}</li> + <li>{{DOMxRef("SVGAnimatedEnumeration")}}</li> + <li>{{DOMxRef("SVGAnimatedInteger")}}</li> + <li>{{DOMxRef("SVGAnimatedLength")}}</li> + <li>{{DOMxRef("SVGAnimatedLengthList")}}</li> + <li>{{DOMxRef("SVGAnimatedNumber")}}</li> + <li>{{DOMxRef("SVGAnimatedNumberList")}}</li> + <li>{{DOMxRef("SVGAnimatedPathData")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGAnimatedPoints")}}</li> + <li>{{DOMxRef("SVGAnimatedPreserveAspectRatio")}}</li> + <li>{{DOMxRef("SVGAnimatedRect")}}</li> + <li>{{DOMxRef("SVGAnimatedString")}}</li> + <li>{{DOMxRef("SVGAnimatedTransformList")}}</li> +</ul> +</div> + +<h3 id="SMIL_related_interfaces" name="SMIL_related_interfaces">SMIL 関連インターフェイス</h3> + +<div class="index"> +<ul> + <li>{{DOMxRef("ElementTimeControl")}}</li> + <li>{{DOMxRef("TimeEvent")}}</li> +</ul> +</div> + +<h3 id="Other_SVG_interfaces" name="Other_SVG_interfaces">その他 SVG インターフェイス</h3> + +<div class="index"> +<ul> + <li>{{DOMxRef("GetSVGDocument")}}</li> + <li>{{DOMxRef("ShadowAnimation")}}</li> + <li>{{DOMxRef("SVGColorProfileRule")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGCSSRule")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGDocument")}}</li> + <li>{{DOMxRef("SVGException")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGExternalResourcesRequired")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGFitToViewBox")}}</li> + <li>{{DOMxRef("SVGLangSpace")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGLocatable")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGRenderingIntent")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGStylable")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGTests")}}</li> + <li>{{DOMxRef("SVGTransformable")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGUnitTypes")}}</li> + <li>{{DOMxRef("SVGUseElementShadowRoot")}}</li> + <li>{{DOMxRef("SVGURIReference")}}</li> + <li>{{DOMxRef("SVGViewSpec")}} {{Deprecated_Inline}}</li> + <li>{{DOMxRef("SVGZoomAndPan")}}</li> + <li>{{DOMxRef("SVGZoomEvent")}} {{Deprecated_Inline}}</li> +</ul> +</div> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + <th scope="col">状態</th> + <th scope="col">備考</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM WHATWG")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Examples">DOM の例</a></li> + <li><a href="/ja/docs/Web/API/CSS_Object_Model">CSS Object Model (CSSOM)</a></li> +</ul> diff --git a/files/ja/web/api/document_object_model/introduction/index.html b/files/ja/web/api/document_object_model/introduction/index.html new file mode 100644 index 0000000000..fb1ccbd31d --- /dev/null +++ b/files/ja/web/api/document_object_model/introduction/index.html @@ -0,0 +1,254 @@ +--- +title: DOM の紹介 +slug: Web/API/Document_Object_Model/Introduction +tags: + - Beginner + - DOM + - Document + - Guide + - HTML DOM + - Introduction + - Tutorial + - 導入 +translation_of: Web/API/Document_Object_Model/Introduction +--- +<p><span class="seoSummary"><strong>Document Object Model</strong> (<strong>DOM</strong>) は、ウェブ上の文書のコンテンツと構造からなるオブジェクトのデータ表現です。このガイドでは、簡単に DOM を紹介します。</span> DOM がどのようにメモリ内で {{Glossary("HTML")}} または {{Glossary("XML")}} の文書を表現するか、どのように API を使用してウェブコンテンツやアプリケーションを作成するのかを見てみます。</p> + +<h2 id="What_is_the_DOM" name="What_is_the_DOM">DOM とは</h2> + +<p>Document Object Model (DOM) は HTML や XML 文書のためのプログラミングインターフェイスです。ページを表現するため、プログラムが文書構造、スタイル、内容を変更することができます。 DOM は文書をノードとオブジェクトで表現します。そうやって、プログラミング言語をページに接続することができます。</p> + +<p>ウェブページは文書です。この文書はブラウザーのウィンドウに表示されるか HTML ソースとして表示することが可能です。しかし両方の場合においてもそれは同じ文書です。ドキュメントオブジェクトモデル (DOM) は、その同じ文書を表現、保存、操作する方法です。DOM はウェブページの完全なオブジェクト指向の表現で、 JavaScript のようなスクリプト言語から変更できます。</p> + +<p><a class="external" href="http://www.w3.org/DOM/">W3C DOM</a> および <a class="external" href="https://dom.spec.whatwg.org">WHATWG DOM</a> 標準は、現代のブラウザーのほとんどで実装されています。多くのブラウザーは標準を拡張しているので、文書が様々なブラウザーの異なる DOM からアクセスされるウェブにおいては注意が必要です。</p> + +<p>例えば、標準 DOM は以下のコードにおける <code>getElementsByTagName</code> メソッドが文書内のすべての <code><p></code> 要素のリストを返さなければならないと定義しています。</p> + +<pre class="brush: js notranslate">const paragraphs = document.getElementsByTagName("p"); +// paragraphs[0] は最初の <p> 要素 +// paragraphs[1] は 2 番目の <p> 要素... +alert(paragraphs[0].nodeName); +</pre> + +<p>ウェブページを操作したり、作成したりするために用意されているすべてのプロパティ、メソッド、イベントは、オブジェクトにまとめられています (例えば、文書自身を表現する <code>document</code> オブジェクトや、 HTML のテーブルにアクセスするための特別な {{domxref("HTMLTableElement")}} DOM インターフェイスを実装した <code>table</code> オブジェクト、などなど)。この文書では DOM について、オブジェクトごとのリファレンスを提供します。</p> + +<p>現在の DOM は協調して動作する複数 API によって構築されています。コア <a href="/ja/docs/Web/API/Document_Object_Model">DOM</a> は、文書やその中のオブジェクトを基礎的に記述するオブジェクトを定義しています。これは必要に応じて DOM に新しい機能や能力を追加する他の API によって拡張されます。例えば、 <a href="/ja/docs/Web/API/HTML_DOM">HTML DOM API</a> はコア DOM に HTML 文書の表現の対応を追加しています。</p> + +<h2 id="DOM_and_JavaScript" name="DOM_and_JavaScript">DOM と JavaScript</h2> + +<p>このリファレンスでの例と同様に、上の短い例は {{glossary("JavaScript")}} で書かれています。つまり、 JavaScript で<em>書かれて</em>いますが、しかし DOM を<em>使用</em>してウェブページとその要素にアクセスしています。 DOM はプログラミング言語ではありませんが、これがないと、 JavaScript 言語はウェブページ、 HTML 文書、 XML 文書、およびその構成部品 (要素など) のモデルや記法を持っていません。文書内のすべての要素 — 全体としての文書、 head、文書内の表、表の見出し、表のセル内のテキスト — は、その文書のドキュメントオブジェクトモデルの一部ですので、 DOM と JavaScript のようなスクリプト言語を通してそれらすべてにアクセスし、操作することができます。</p> + +<p>当初、 JavaScript と DOM は密接に絡み合っていましたが、最終的には別々の存在に進化しました。ページの内容は DOM に格納されており、 JavaScript を介してアクセスしたり操作したりすることができるので、この近似式を書くことができます。</p> + +<p>API = DOM + JavaScript</p> + +<p>DOM は特定のプログラミング言語に依存しないように設計されており、文書の構造表現を単一の一貫した API から利用できるようになっています。このリファレンス文書では JavaScript のみに焦点を当てていますが、この Python の例が示すように、DOM の実装はどのような言語にも対応できるようになっています。</p> + +<pre class="brush: python notranslate"># Python DOM example +import xml.dom.minidom as m +doc = m.parse(r"C:\Projects\Py\chap1.xml") +doc.nodeName # DOM property of document object +p_list = doc.getElementsByTagName("para") +</pre> + +<p>ウェブで JavaScript を書くためにどのような技術が使われるのかについての詳細は、 <a href="/ja/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript 技術概要</a>をご覧ください。</p> + +<h2 id="How_Do_I_Access_the_DOM.3F" name="How_Do_I_Access_the_DOM.3F">DOM へのアクセス</h2> + +<p>DOM を使い始めるには、何も特別なものは必要ありません。異なるブラウザーは異なる DOM の実装をもっています。そして、これらの実装の実際の DOM の規格への適応度はさまざまです (この話題に関してはこの文書では避けます)。しかし、すべてのウェブラウザーはスクリプトからウェブページにアクセスできるように何らかのドキュメントオブジェクトモデルを持っています。</p> + +<p>インラインの <code><script></code> 要素であろうとも、スクリプトを読み込む命令によってウェブページに埋め込まれていようとも、スクリプトを作れば、 {{domxref("document")}} や {{domxref("Window", "window")}} 要素といったウェブページ中のさまざまな要素に対するに API をすぐに使い始めることが出来ます。それらの API で文書自身を操作したり、文書の子要素を取り出したりできます。 DOM でのプログラミングは以下のように簡単に出来ます。1 つは、 {{domxref("Window", "window")}} オブジェクトの {{domxref("Window.alert", "alert()")}} 関数を利用し、警告メッセージを表示しています。より長い例はより洗練された DOM 関数を使い、実際に新しいコンテンツを作り出しています。</p> + +<p>以下の JavaScript は、文書が読み込まれた時 (として DOM が利用可能になった時) にアラートを表示します。</p> + +<pre class="brush: html notranslate"><body onload="window.alert('私のホームページへようこそ!');"> +</pre> + +<p>他の例です。この関数は新しい H1 要素を作成し、その要素にテキストを加え、文書のツリーに <code>H1</code> 要素を加えています。</p> + +<pre class="brush: html notranslate"><html> + <head> + <script> + // この関数は文書が読みこまれた時に実行される + window.onload = function() { + + // create a couple of elements in an otherwise empty HTML page + const heading = document.createElement("h1"); + const heading_text = document.createTextNode("Big Head!"); + heading.appendChild(heading_text); + document.body.appendChild(heading); + } + </script> + </head> + <body> + </body> +</html> +</pre> + +<h2 id="Important_Data_Types" name="Important_Data_Types">基本的なデータ型</h2> + +<p>このリファレンスでは、様々なオブジェクトと種類をなるべく簡単な方法で説明します。しかし、API に渡される、注意しなければならないデータ型はたくさんあります。</p> + +<div class="blockIndicator note"> +<p><strong>注:</strong> DOM を使用するコードの大部分は HTML 文書の操作を中心としているため、DOM 内のノードを<strong>要素</strong>と呼ぶのが一般的ですが、厳密にはすべてのノードが要素というわけではありません。</p> +</div> + +<p>以下の表はこれらのデータの種類を簡単に説明しています。</p> + +<table class="standard-table"> + <thead> + <tr> + <th>データ型 (インターフェイス)</th> + <th>説明</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("Document")}}</td> + <td>メンバーが <code>document</code> 型のオブジェクトを返すときは (例えば、element の <code>ownerDocument</code> 属性はそれが属する <code>document</code> を返します)、このオブジェクトはルートの <code>document</code> オブジェクト自身です。<a href="/ja/docs/Web/API/Document">DOM の <code>document</code> リファレンス</a>の章は <code>document</code> オブジェクトを説明しています。</td> + </tr> + <tr> + <td>{{domxref("Node")}}</td> + <td>文書内にあるすべてのオブジェクトは何らかの種類のノードです。 HTML 文書では、オブジェクトは要素ノードだけでなく、テキストノードや属性ノードもあります。</td> + </tr> + <tr> + <td>{{domxref("Element")}}</td> + <td><code>element</code> 型は <code>node</code> に基づいています。これは要素、または DOM API のメンバーから返される <code>element</code> 型のノードのことです。例えば、 {{domxref("document.createElement()")}} メソッドは <code>node</code> へのオブジェクト参照を返すというより、このメソッドは単に DOM によって生成された <code>element</code> を返すと言えます。 <code>element</code> オブジェクトは DOM の <code>Element</code> インターフェイスと、もっと基本的な <code>Node</code> インターフェイスも実装しており、両方がこの参照に含まれます。 HTML 文書では、要素はさらに HTML DOM API の {{domxref("HTMLElement")}} インターフェイスや、特定の種類の要素における能力を記述するためのその他のインターフェイス (例えば {{HTMLElement("table")}} 要素における {{domxref("HTMLTableElement")}}) によって更に拡張されています。</td> + </tr> + <tr> + <td>{{domxref("NodeList")}}</td> + <td><code>nodeList</code> は、 {{domxref("document.getElementsByTagName()")}} で返されるものなど要素の配列です。 <code>nodeList</code> 中の項目は、インデックスを使って以下の2つの方法で取得できます。 + <ul> + <li>list.item(1)</li> + <li>list[1]</li> + </ul> + この二つの方法は等価です。最初の方法では、 <code>item()</code> は <code>nodeList</code> オブジェクトの一つの関数です。後者の方は、一般的な配列の構文を使い、リスト中の二つ目の項目を取得しています。</td> + </tr> + <tr> + <td>{{domxref("Attribute")}}</td> + <td><code>attribute</code> が (<code>createAttribute()</code> メソッドなどの) メンバーから返されたとき、属性のための特別な (ただし、小さな) インターフェイスを実装したオブジェクトの参照です。属性は要素のような DOM のノードですが、さほど使われません。</td> + </tr> + <tr> + <td>{{domxref("NamedNodeMap")}}</td> + <td><code>namedNodeMap</code> は配列のようですが、名前またはインデックスによって項目にアクセスきますが、後者は項目がリスト中に特定の順番で並んでいる訳ではないので、列挙するのに便利であるだけです。このために <code>namedNodeMap</code> には <code>item()</code> メソッドがあり、 <code>namedNodeMap</code> に項目を追加したり、削除したりすることができます。</td> + </tr> + </tbody> +</table> + +<p>注意すべき用語の使い方がいくつかあります。例えば、ある {{domxref("Attribute")}} ノードを参照するのに単に <code>attribute</code> と呼んだり、 DOM ノードの配列を参照するのに <code>nodeList</code> と呼んだりします。このような用語は文書を通して紹介され使用されているのが分かるでしょう。</p> + +<h2 id="DOM_interfaces" name="DOM_interfaces">DOM インタフェース</h2> + +<p>このガイドは、 DOM 階層構造を操作するために利用できるオブジェクトと、実際の<em>もの</em>について触れます。どのように動作するかを理解する上で、混乱を催すかもしれない点がたくさんあります。例えば、 HTML の <code>form</code> 要素を表すオブジェクトには、 <code>name</code> プロパティが <code>HTMLFormElement</code> インターフェイスにある一方、 <code>className</code> プロパティが <code>HTMLElement</code> インターフェイスにあります。どちらにしても、求めるプロパティはその form オブジェクトの中にあります。</p> + +<p>しかし、 DOM で実装されているオブジェクトとインターフェイスの関係は複雑なので、この節では、 DOM の仕様での実際のインターフェイスとそれがどのように利用できるかについて少し説明しようと思います。</p> + +<h3 id="Interfaces_and_Objects" name="Interfaces_and_Objects">インターフェイスとオブジェクト</h3> + +<p>多くのオブジェクトは複数のインターフェイスを受けついでいます。例えば、 table オブジェクトでは、特別な {{domxref("HTMLTableElement")}} インターフェイスを実装しており、そのインターフェイスは <code>createCaption</code> や <code>insertRow</code> などのメソッドを含んでいます。しかし、 <code>table</code> は HTML の要素でもあるので、 DOM の {{domxref("Element")}} リファレンスの章で説明している <code>Element</code> インターフェイスも実装しています。さらには、 HTML の要素は、 DOM を考慮する限り、ウェブページや XML ページのオブジェクトモデルを作りあげるノードのツリー内にあるノードもであるので、 table オブジェクトはより基本的な <code>Node</code> インターフェイスを、 <code>Element</code> から継承して実装しています。</p> + +<p>次の例のように、 <code>table</code> オブジェクトの参照を入手したときは、おそらく無意識に、このオブジェクトの三つのインターフェイスをごく普通に交互に使います。</p> + +<pre class="brush: js notranslate">const table = document.getElementById("table"); +const tableAttrs = table.attributes; // Node/Element インターフェイス +for (let i = 0; i < tableAttrs.length; i++) { + // HTMLTableElement インターフェイス: border 属性 + if(tableAttrs[i].nodeName.toLowerCase() == "border") + table.border = "1"; +} +// HTMLTableElement インターフェイス: summary 属性 +table.summary = "注意: 太くなった枠線"; +</pre> + +<h3 id="Core_Interfaces_in_the_DOM" name="Core_Interfaces_in_the_DOM">DOM の中で核となるインターフェイス</h3> + +<p>この節では、 DOM の中で最もよく使われるインターフェイスを列挙します。API がここで何をしているか記述するのではなく、DOM の中で非常に良く使われる関数や属性をちょっと示すのが狙いです。これらよく使われる API はこの本の最後の <a href="/ja/docs/Web/API/Document_Object_Model/Examples">DOM の例</a>の章のより長い例の中で使われています。</p> + +<p><code>document</code> と <code>window</code> オブジェクトが一般的に DOM プログラミングの中で最もよく使われます。簡単に言うと、 <code>window</code> オブジェクトはブラウザーのようなものを表現し、 <code>document</code> オブジェクトは文書のルート自身です。 <code>Element</code> は一般的な <code>Node</code> インターフェイスを継承していて、あわせてこの 2 つのインターフェイスはここの要素で使われる多くの関数と属性を提供します。前節での <code>table</code> オブジェクトの例のように、これの要素はそれぞれが持つデータを扱うための特定のインターフェイスを持っている場合があります。</p> + +<p>以下は、 DOM を使うウェブや XML ページのスクリプトでよく使われる API の簡単な一覧です。</p> + +<ul> + <li><code>{{domxref("document.getElementById", "", "", "1")}}(id)</code></li> + <li><code>document.{{domxref("Element.getElementsByTagName", "getElementsByTagName", "", "1")}}(name)</code></li> + <li><code>{{domxref("document.createElement", "", "", "1")}}(name)</code></li> + <li><code>parentNode.{{domxref("Node.appendChild", "appendChild", "", "1")}}(node)</code></li> + <li><code>element.{{domxref("element.innerHTML", "innerHTML", "", "1")}}</code></li> + <li><code>element.{{domxref("HTMLElement.style", "style", "", "1")}}.left</code></li> + <li><code>element.{{domxref("element.setAttribute", "setAttribute", "", "1")}}()</code></li> + <li><code>element.{{domxref("element.getAttribute", "getAttribute", "", "1")}}()</code></li> + <li><code>element.{{domxref("EventTarget.addEventListener", "addEventListener", "", "1")}}()</code></li> + <li><code>{{domxref("window.content", "", "", "1")}}</code></li> + <li><code>{{domxref("window.onload", "", "", "1")}}</code></li> + <li><code>{{domxref("window.scrollTo", "", "", "1")}}()</code></li> +</ul> + +<h2 id="Testing_the_DOM_API" name="Testing_the_DOM_API">DOM API のテスト</h2> + +<p>この文書は、ウェブ開発に利用できるあらゆるインターフェイスの例を提供しています。いくつかの場合では、サンプルは完全な HTML ページで、これは DOM アクセスは <script> 要素の中に入っており、フォームのスクリプトを起動するのに必要なインターフェイス (例えば、ボタン) があり、DOM が操作する HTML 要素がリストされています。この場合は、例を新しい HTML 文書にカット・アンド・ペーストし、保存し、ブラウザーから例を走らせることができます。</p> + +<p>しかし、いくつかのケースでは例はより簡潔です。HTML 要素のインターフェイスの基本的な関係を示すだけの例を走らせるために、インターフェイスがスクリプトから簡単にアクセスできるようなテストページを準備したいと思うかもしれません。以下の非常に簡単なウェブページはインターフェイスをテストする関数をおけるようにするヘッダー中の <script> 要素と、習得・設定・操作できる属性を持ったいくつかの HTML 要素と、ブラウザーからこれらの関数を呼ぶのに必要なウェブのユーザーインターフェイスを提供しています。</p> + +<p>あなたが興味のある DOM インターフェイスをテストするために、このテストページや似たようなものを作ることができますし、ブラウザー上でどのように動くか見れます。必要であれば <code>test()</code> 関数の中身を更新したり、もっとボタンを作ったり、必要な要素を追加したりできます。</p> + +<pre class="brush: html notranslate"><html> +<head> + <title>DOM Tests</title> + <script> + function setBodyAttr(attr, value) { + if (document.body) document.body[attr] = value; + else throw new Error("no support"); + } + </script> +</head> +<body> + <div style="margin: .5in; height: 400px;"> + <p><b><tt>text</tt></b></p> + <form> + <select onChange="setBodyAttr('text', + this.options[this.selectedIndex].value);"> + <option value="black">black</option> + <option value="red">red</option> + </select> + <p><b><tt>bgColor</tt></b></p> + <select onChange="setBodyAttr('bgColor', + this.options[this.selectedIndex].value);"> + <option value="white">white</option> + <option value="lightgrey">gray</option> + </select> + <p><b><tt>link</tt></b></p> + <select onChange="setBodyAttr('link', + this.options[this.selectedIndex].value);"> + <option value="blue">blue</option> + <option value="green">green</option> + </select> + <small> + <a href="http://some.website.tld/page.html" id="sample"> + (sample link) + </a> + </small><br /> + <input type="button" value="version" onclick="ver()" /> + </form> + </div> +</body> +</html> +</pre> + +<p>例えば、ウェブページの色に影響する一連の属性のように、たくさんのインターフェイスを一つのページでテストするために、ボタンやテキスト入力欄、その他の HTML 要素を全部集めた似たようなテストページを作ることができます。以下のスクリーンショットは、インターフェイスをテストのために一緒にまとめる方法のアイディアを示します。</p> + +<figure> +<figcaption>図 0.1 DOM テストページの例</figcaption> +<img alt="画像:DOM_Ref_Introduction_to_the_DOM.gif" class="internal" src="/@api/deki/files/173/=DOM_Ref_Introduction_to_the_DOM.gif"></figure> + +<p>この例では、ウェブページの DOM からアクセス可能であるという側面から、ドロップダウンメニューの背景色 (<code>bgColor</code>) やハイパーリンクの色 (<code>aLink</code>) や文字色 (<code>text</code>) を動的に更新します。しかし、読んだことについてインターフェイスをテストするテストページを設計してみることは、 DOM の使い方を効果的に学ぶ上で重要なことです。</p> + +<h2 id="Subnav">Subnav</h2> + +<ul> + <li><a href="/ja/docs/Web/API/Document_Object_Model">DOM リファレンス</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Introduction">DOM の紹介</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Events">イベントと DOM</a></li> + <li><a href="/ja/docs/Web/API/Document_Object_Model/Examples">例</a></li> +</ul> + +<div>{{DefaultAPISidebar("DOM")}}</div> diff --git a/files/ja/web/api/document_object_model/locating_dom_elements_using_selectors/index.html b/files/ja/web/api/document_object_model/locating_dom_elements_using_selectors/index.html new file mode 100644 index 0000000000..e3f06590b7 --- /dev/null +++ b/files/ja/web/api/document_object_model/locating_dom_elements_using_selectors/index.html @@ -0,0 +1,50 @@ +--- +title: セレクターを使用した DOM 要素の特定 +slug: Web/API/Document_object_model/Locating_DOM_elements_using_selectors +tags: + - Beginner + - DOM + - NeedsBeginnerUpdate +translation_of: Web/API/Document_object_model/Locating_DOM_elements_using_selectors +--- +<p>セレクター API により提供されるメソッドを用いると、一連のセレクターに一致する {{domxref("Element")}} (要素) ノードを DOM から簡単かつ素早く取り出すことができます。これは過去の技術よりもはるかに速く、必要な場所で、例えば、 JavaScript コードでループを使用して検索する必要があるアイテムを特定するために使います。</p> + +<h2 id="The_NodeSelector_interface" name="The_NodeSelector_interface">NodeSelector インターフェース</h2> + +<p>この仕様書では、 {{domxref("Document")}}, {{domxref("DocumentFragment")}}, {{domxref("Element")}} インターフェースを実装しているすべてのオブジェクトに対して二つの新しいメソッドを追加します。</p> + +<dl> + <dt>{{domxref("Element.querySelector", "querySelector()")}}</dt> + <dd>ノードのサブツリー内で最初に一致した {{domxref("Element")}} ノードを返します。一致する要素がなかった場合は <code>null</code> を返します。</dd> + <dt>{{domxref("Element.querySelectorAll", "querySelectorAll()")}}</dt> + <dd>ノードのサブツリー内で一致するすべての <code>Element</code> ノードを含む {{domxref("NodeList")}} を返すか、一致するものが見つからなかった場合は空の <code>NodeList</code> を返します。</dd> +</dl> + +<div class="note"><strong>注:</strong> {{domxref("Element.querySelectorAll()", "querySelectorAll()")}} が返す {{domxref("NodeList")}} はライブではありません。すなわち、 DOM で行われた変更がコレクションに反映されません。これは他の DOM クエリメソッドがライブのノードリストを返すのと異なります。</div> + +<p>例や詳細については、 {{domxref("Element.querySelector()")}} および {{domxref("Element.querySelectorAll()")}} メソッドの文書や、 <a href="/ja/docs/Code_snippets/QuerySelector" title="Code snippets/QuerySelector">querySelector のコードスニペット</a>などにあります。</p> + +<h2 id="Selectors" name="Selectors">セレクター</h2> + +<p>セレクターのメソッドには、カンマで区切られた一つ以上の抽出対象の要素を指定します。例えば、文書中で CSS のクラスが <code>warning</code> または <code>note</code> に指定されている全ての段落要素 (<code>p</code>) を抽出するには、次のようにします。</p> + +<pre class="notranslate"><code>var special = document.querySelectorAll( "p.warning, p.note" );</code></pre> + +<p>もちろん、 ID による指定も可能です。例えば:</p> + +<pre class="notranslate"><code>var el = document.querySelector( "#main, #basic, #exclamation" );</code></pre> + +<p>上記のコードが実行されると、<code>el</code> には ID が <code>main</code>、 <code>basic</code>、 <code>exclamation</code> である要素の内、最初の要素だけが格納されます。</p> + +<p>例で示したように、 <code>querySelector()</code> や <code>querySelectorAll()</code> メソッドではどの CSS セレクタでも用いることができます。</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/selectors-api/" title="http://www.w3.org/TR/selectors-api/">Selectors API</a></li> + <li>{{domxref("Element.querySelector()")}}</li> + <li>{{domxref("Element.querySelectorAll()")}}</li> + <li>{{domxref("Document.querySelector()")}}</li> + <li>{{domxref("Document.querySelectorAll()")}}</li> + <li><a href="/ja/docs/Code_snippets/QuerySelector" title="ja/docs/Code_snippets/QuerySelector">Code snippets for querySelector</a></li> +</ul> diff --git a/files/ja/web/api/document_object_model/preface/index.html b/files/ja/web/api/document_object_model/preface/index.html new file mode 100644 index 0000000000..81f37f4850 --- /dev/null +++ b/files/ja/web/api/document_object_model/preface/index.html @@ -0,0 +1,51 @@ +--- +title: 序文 +slug: Web/API/Document_Object_Model/Preface +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/Document_Object_Model +--- +<div> + {{ApiRef}}</div> +<h2 id="About_This_Reference" name="About_This_Reference">この資料について</h2> +<p>この節では、このガイドそのものについて説明します。誰のための資料で、どんな情報があって、あなた独自の DOM 開発を行うにあたってこの資料のなかの例をどのように使えるのか、について説明します。</p> +<p>この文書は書きかけなので、Gecko に実装されている DOM 関数と属性がきれいにまとめられてはいません。ただし、資料に含まれる各オブジェクトに関する文書 (<a href="/ja/docs/DOM/document" title="DOM/document">DOM Document リファレンス</a> など) は完結しています。多数の API に含まれるさまざまな資料が準備でき次第、この資料に追加します。</p> +<h2 id="Who_Should_Read_This_Guide" name="Who_Should_Read_This_Guide">この資料の対象となる読者</h2> +<p><a href="/ja/docs/DOM/DOM_Reference" title="DOM/DOM_Reference">Gecko DOM リファレンス</a> の読者は web 開発者や web ページの仕組みを知っている web の利用者です。この資料では、読者の専門知識を前提とはしていません。DOM、<a href="/ja/docs/XML" title="XML">XML</a>、web サーバ、web 標準、読者が DOM にアクセスするための言語である <a href="/ja/docs/JavaScript" title="JavaScript">JavaScript</a> に関する知識があるとは限らないものとしています。ですが、web ページの基本である <a href="/ja/docs/HTML" title="HTML">HTML</a> とブラウザとスタイルシートなどは押さえているものとして書かれています。</p> +<p>「導入の記述がある」 「例が多様」 「説明が詳しい」 という点では、「初心者向け」 のハッキングガイドと言うこともできます。ただし、一般的に言って、技術資料というものは web 開発の経験があっても無くても、その人たちにとって有用な資料である必要があります。</p> +<h2 id="What_is_Gecko.3F" name="What_is_Gecko.3F">Gecko とは?</h2> +<p>Mozilla と Firefox、Netscape 6 以上、そのほかの Mozilla をもとにしたブラウザの DOM 実装は同一のものです。というのも、これらのブラウザは同じ技術を使用しているからです。<span class="comment">naturally, it applies only to products based on the same version of Gecko, but it's tricky to explain</span></p> +<p>Gecko はこれらのブラウザの中にあるソフトウェアコンポーネントのことで、HTML の解析、ページのレイアウト、ドキュメント・オブジェクト・モデル、そしてアプリケーション・インタフェースの描画も処理しています。Gecko は、速く、標準に準拠した描画エンジンで、W3C の DOM 標準や DOM に類似した(しかし標準化されていない)ブラウザ・オブジェクト・モデル(例:<a href="/ja/docs/DOM/window" title="DOM/window"><code>window</code></a> など)を、web ページやブラウザのアプリケーション・インタフェース(<em>chrome</em>)において、実装します。</p> +<p>ブラウザによって表示されるアプリケーション・インタフェースやコンテントは実際には異なりますが、DOM はこれらを一律にノードの階層として提示します。<span class="comment">(commenting this incomplete sentence out for now...) The tree structure of the DOM (which in its application to the user</span></p> +<h2 id="API_Syntax" name="API_Syntax">API 構文</h2> +<p>各資料には、構文、入出力の引数 (return 型が与えられている return 型の場所) 、例、補足、該当仕様へのリンクがあります。</p> +<p>とくに読みとり専用属性の文法は基本的に一行だけです。なぜなら、それらのプロパティは設定できずアクセスしかできないからです。例えば、<code>screen</code> オブジェクトの <code>availHeight</code> は読取専用の属性なので、次のような構文で書かれています。</p> +<pre class="brush:js">iAvail = window.screen.availHeight +</pre> +<p>つまり、式の右辺の属性だけが利用できるということです。それに対して、読み書き可能な属性の場合は、次の例でも分かるように、値を設定することもできます。</p> +<pre class="brush:js">msg = window.status +window.status = msg +</pre> +<p>一般に、メンバの記述があるオブジェクトの場合、その構文は簡潔な型になります。例えば、要素ならなんでも <code>element</code> ですし、document オブジェクトなら <code>document</code> ですし、TABLE オブジェクトなら <code>TABLE</code> といった具合です (データ型について詳しくは<a href="/ja/docs/DOM/DOM_Reference/Introduction#Important_Data_Types" title="DOM/DOM_Reference/Introduction#Important_Data_Types">重要なデータ型</a> を参照してください)。</p> +<h2 id="Using_the_Examples" name="Using_the_Examples">例の使い方</h2> +<p>資料にある例のうち、その多くは単独のファイルとして完結しているものです。新しいファイルにコピーしてブラウザで開くと、きちんと動作します。コード断片もあります。断片の場合は、その断片を JavaScript コールバック関数内で使うことができます。例えば、 <a href="/ja/docs/DOM/window.document" title="DOM/window.document">window.document</a> 属性の資料にある例を次のように関数内に入れて、ボタンが押されたら呼ばれるような確認コードを書くことができます。</p> +<pre class="brush:html"><!DOCTYPE html> +<html> +<head> +<title>Test Page</title> +<script> +function testWinDoc() { + doc = window.document; + alert(doc.title); +} +</script> +</head> + +<body> + <button onclick="testWinDoc();">test document property</button> +</body> +</html> +</pre> +<p>すぐに利用できるように梱包されていないオブジェクトのメンバーについても、上記のような関数やページを作り出すことができます。「テスト実行環境」 の導入部分にある <a href="/ja/docs/DOM/DOM_Reference/Introduction#Testing_the_DOM_API" title="DOM/DOM_Reference/Introduction#Testing_the_DOM_API">DOM API のテスト</a> の節を参照してください。それを使うと、一度に、たくさんの API の動作を確認できます。</p> diff --git a/files/ja/web/api/document_object_model/traversing_an_html_table_with_javascript_and_dom_interfaces/index.html b/files/ja/web/api/document_object_model/traversing_an_html_table_with_javascript_and_dom_interfaces/index.html new file mode 100644 index 0000000000..53863ac83c --- /dev/null +++ b/files/ja/web/api/document_object_model/traversing_an_html_table_with_javascript_and_dom_interfaces/index.html @@ -0,0 +1,366 @@ +--- +title: Java Scirpt と DOM インターフェイスによる HTML の表の操作 +slug: >- + Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces +tags: + - API + - DOM + - Guide + - HTML + - JavaScript +translation_of: >- + Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces +--- +<p>{{DefaultAPISidebar("DOM")}}</p> + +<h2 id="Introduction" name="Introduction">はじめに</h2> + +<p>この記事では、強力で基本的な DOM レベル 1 のメソッドと、それを JavaScript からどのように使用するかを概観します。どのようにして HTML 要素を動的に生成、アクセス、制御、削除するかを学ぶことができます。ここで紹介する DOM メソッドは HTML に限ったものではなく、XML に対しても用いることができます。ここで用意しているデモは、 Firefox のすべてのバージョンや IE 5以上を含むすべての最近のブラウザーで正常に動作します。</p> + +<div class="blockIndicator note"> +<p>ここで紹介する DOM メソッドは ドキュメントオブジェクトモデル (コア) レベル 1 仕様の一部に過ぎません。 DOM レベル 1 には HTML ドキュメント特有のメソッド (DOM 1 HTML) と共に、一般的なドキュメントアクセスと操作 (DOM 1 コア) のためのメソッドが含まれています。</p> +</div> + +<h2 id="Overview_of_Sample1.html" name="Overview_of_Sample1.html">例: 動的な HTML の表の生成 (<code>Sample1.html</code>)</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html; notranslate"><input type="button" value="Generate a table." onclick="generate_table()"> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js; notranslate">function generate_table() { + // get the reference for the body + var body = document.getElementsByTagName("body")[0]; + + // creates a <table> element and a <tbody> element + var tbl = document.createElement("table"); + var tblBody = document.createElement("tbody"); + + // creating all cells + for (var i = 0; i < 2; i++) { + // creates a table row + var row = document.createElement("tr"); + + for (var j = 0; j < 2; j++) { + // Create a <td> element and a text node, make the text + // node the contents of the <td>, and put the <td> at + // the end of the table row + var cell = document.createElement("td"); + var cellText = document.createTextNode("セルは "+i+" 行 "+j+" 列 です"); + cell.appendChild(cellText); + row.appendChild(cell); + } + + // add the row to the end of the table body + tblBody.appendChild(row); + } + + // put the <tbody> in the <table> + tbl.appendChild(tblBody); + // appends <table> into <body> + body.appendChild(tbl); + // sets the border attribute of tbl to 2; + tbl.setAttribute("border", "2"); +}</pre> + +<p>{{ EmbedLiveSample('Overview_of_Sample1.html') }}</p> + +<p>要素とテキストノードを生成する順序を意識しながら確認していってください。</p> + +<ol> + <li>まず、 <code><table></code> 要素を生成しました。</li> + <li>次に <code><tbody></code> 要素生成し、これが <code><table></code> 要素の子となります。</li> + <li>次に、ループを用いて <code><tr></code> 要素を生成し、これらが <code><tbody></code> 要素の子となります。</li> + <li>それぞれの <code><tr></code> 要素に対して、ループを用いて <code><td></code> 要素を生成し、これらが <code><tr></code> の子となります。</li> + <li>それから、それぞれの <code><td></code> 要素に対して、表のセルのテキストノードとテキストを生成しました。</li> +</ol> + +<p><code><table></code>, <code><tbody></code>, <code><tr></code>, <code><td></code> の各要素とテキストノードを生成したら、逆の順序でそれぞれのオブジェクトを親へ追加していきます。</p> + +<ol> + <li>まず、各テキストノードをその親である <code><td></code> 要素へ追加します。 + + <pre class="notranslate">cell.appendChild(cellText);</pre> + </li> + <li>次に、各 <code><td></code> 要素をその親である <code><tr></code> 要素へと追加します。 + <pre class="notranslate">row.appendChild(cell);</pre> + </li> + <li>次に、各 <code><tr></code> 要素をその親である <code><tbody></code> 要素へと追加します。 + <pre class="notranslate">tblBody.appendChild(row);</pre> + </li> + <li>次に、 <code><tbody></code> 要素をその親である <code><table></code> 要素へと追加します。 + <pre class="notranslate">tbl.appendChild(tblBody);</pre> + </li> + <li>次に、 <code><table></code> 要素をその親である <code><body></code> 要素へと追加します。 + <pre class="notranslate">body.appendChild(tbl);</pre> + </li> +</ol> + +<p>この手法を覚えておきましょう。 W3C DOM によるプログラミングでは頻繁に使うことになります。まず、トップダウンで要素を作成し、子を親へとボトムアップで追加していくのです。</p> + +<p>JavaScript コードによって生成される HTML マークアップはこのようになります。</p> + +<pre class="notranslate">... +<table border="2"> +<tbody> +<tr><td>セルは 0 行 0 列 です</td><td>セルは 0 行 1 列 です</td></tr> +<tr><td>セルは 1 行 0 列 です</td><td>セルは 1 行 1 列 です</td></tr> +</tbody> +</table> +... +</pre> + +<p>このコードによって生成される <code><table></code> 要素とその子要素を示す DOM オブジェクトツリーはこのようになります。</p> + +<p><img alt="Image:sample1-tabledom.jpg" src="/@api/deki/files/833/=Sample1-tabledom.jpg"></p> + +<p>ほんの幾つかの DOM メソッドを使用するだけでこのように表と内部の子要素を構築できます。生成しようと計画している構造のツリーモデルを頭に置いておくことを忘れないようにしてください。そうすれば必要なコードを書くのは簡単です。図 1 の <code><table></code> ツリーでは <code><table></code> 要素は <code><tbody></code> 要素という子を 1 つ持ちます。<code><tbody></code> は 2 つ子を持ちます。各 <code><tbody></code> の子 (<code><tr></code>) は子を 1 つ (<code><td></code>) 持ちます。最後に各 <code><td></code> はテキストノードという子を 1 つ持ちます。</p> + +<h2 id="Setting_background_of_a_paragraph" name="Setting_background_of_a_paragraph">例: 段落の背景色の設定</h2> + +<p><code>getElementsByTagName(tagNameValue)</code> は DOM の {{domxref("Element")}} および ルートの {{domxref("Document")}} 要素で利用することができます。呼び出すと、その要素の配下でタグ名が一致するすべての要素の配列を返します。リスト中の先頭の要素は、配列内の <code>[0]</code> の位置にあります。</p> + +<h3 id="HTML_2">HTML</h3> + +<pre class="brush: html; notranslate"><body> + <input type="button" value="Set paragraph background color" onclick="set_background()"> + <p>hi</p> + <p>hello</p> +</body></pre> + +<h3 id="JavaScript_2">JavaScript</h3> + +<pre class="brush: js; notranslate">function set_background() { + // body 要素全てのリストを取得します (あるのは 1 つだけですが) + // それからその要素の 0 番目 (最初) の要素を選択します + myBody = document.getElementsByTagName("body")[0]; + + // 今度は body の子供である p 要素を全て取得します + myBodyElements = myBody.getElementsByTagName("p"); + + // p 要素のリストから 2 番目の項目を取得します + myP = myBodyElements[1]; + myP.style.background = "rgb(255,0,0)"; +}</pre> + +<p>{{ EmbedLiveSample('Setting_background_of_a_paragraph') }}</p> + +<p>この例では、<code>myP</code> 変数を body 中の 2 つ目の <code>p</code> 要素を表す DOM オブジェクトに設定しています。</p> + +<ol> + <li>まず、全ての body 要素リストをこのようにして取得します。 + <pre class="notranslate">myBody = document.getElementsByTagName("body")[0]</pre> + 有効な HTML 文書では body 要素は 1 つしかないため、このリストは 1 項目だけを持ちます。そのリストの最初の要素を <code>[0]</code> を使って選択することで取得します。</li> + <li>次に、 <code>body</code> の子である全ての <code>p</code> 要素をこのようにして取得します。 + <pre class="notranslate">myBodyElements = myBody.getElementsByTagName("p");</pre> + </li> + <li>そして <code>p</code> 要素のリストから二つ目の項目をこのようにして取得します。 + <pre class="notranslate">myP = myBodyElements[1];</pre> + </li> +</ol> + +<p><img alt="Image:sample2a2.jpg" src="/@api/deki/files/834/=Sample2a2.jpg"></p> + +<p>一旦 HTML 要素に対応する DOM オブジェクトを取得すれば、そのプロパティを設定することできます。例えば、背景色のスタイルプロパティを設定したいのであればこのように加えるだけです。</p> + +<pre class="notranslate">myP.style.background = "rgb(255,0,0)"; +// インラインの STYLE 属性を設定 +</pre> + +<h3 id="Creating_TextNodes_with_document.createTextNode.28.22...22.29" name="Creating_TextNodes_with_document.createTextNode.28.22...22.29">document.createTextNode("..") によるテキストノードの生成</h3> + +<p>document オブジェクトを使用して <code>createTextNode</code> メソッドを呼び出し、テキストノードを生成します。テキスト内容を渡す必要があるだけです。返値はそのテキストノードを表すオブジェクトとなります。</p> + +<pre class="notranslate">myTextNode = document.createTextNode("world"); +</pre> + +<p>これはそのテキストデータが「world」である <code>TEXT_NODE</code> 型 (テキスト断片) のノードを生成し、myTextNode がこのノードオブジェクトへの参照だということです。このテキストを HTML ページに挿入するには、このテキストノードを何か他のノード要素の子供にする必要があります。</p> + +<h3 id="Inserting_Elements_with_appendChild.28...29" name="Inserting_Elements_with_appendChild.28...29">appendChild(..) による要素の挿入</h3> + +<p>そこで myP.appendChild({{ mediawiki.external('ノード要素') }}) を使って、その要素を 2 つ目の <code><p></code> 要素の子とします。</p> + +<pre class="notranslate">myP.appendChild(myTextNode); +</pre> + +<p>例を見て頂いたところで、単語 hello と world が一緒になっていることに注目して下さい: helloworld。ご覧のように外見的には、HTML ページを見ると 2 つのテキスト hello と world は単一ノードのように見えますが、ドキュメントモデルでは 2つのノードがあるのです。 2つ目のノードは <code>TEXT_NODE</code> 型の新しいノードで、2つ目の <code><p></code> タグの 2つ目の子供です。以下の図は文書ツリー中につい先程生成された Text Node オブジェクトを表しています。</p> + +<p><img alt="Image:sample2b2.jpg" src="/@api/deki/files/835/=Sample2b2.jpg"></p> + +<div class="blockIndicator note"> +<p><code>createTextNode()</code> と <code>appendChild</code> は、 hello と world という単語の間にホワイトスペースを入れる簡単な方法です。もう一つの重要な注意点は、 hello の後に world という単語が追加されたように、 <code>appendChild</code> メソッドは最後の子の後に子を追加するということです。ですから、 hello と world の間にテキストノードを追加したい場合は、 <code>appendChild</code> の代わりに <code>appendChild</code> を使用する必要があります。</p> +</div> + +<h3 id="Creating_New_Elements_with_the_document_object_and_the_createElement.28...29_method" name="Creating_New_Elements_with_the_document_object_and_the_createElement.28...29_method">文書オブジェクトと createElement(..) メソッドによる新しい要素の生成</h3> + +<p>createElement を使って、新しい HTML 要素やその他の任意の要素を作成することができます。例えば、 <body> 要素の子として新しい <p> 要素を作成したい場合は、先ほどの例の <code>myBody</code> を使用して、新しい要素ノードを追加します。ノードを作成するには、単に <code>document.createElement("タグ名")</code> を呼び出すだけです。例えば、以下のようになります。</p> + +<pre class="notranslate">myNewPTAGnode = document.createElement("p"); +myBody.appendChild(myNewPTAGnode); +</pre> + +<p><img alt="Image:sample2c.jpg" src="/@api/deki/files/836/=Sample2c.jpg"></p> + +<h3 id="Removing_nodes_with_the_removeChild.28...29_method" name="Removing_nodes_with_the_removeChild.28...29_method">removeChild(..) メソッドによるノードの削除</h3> + +<p>ノードを削除することができます。以下のコードは、テキストノード <code>myTextNode</code> ("world" という単語を含む) を2番目の <code><p></code> 要素である <code>myP</code> から削除します。</p> + +<pre class="notranslate">myP.removeChild(myTextNode); +</pre> + +<p>テキストノード <code>myTextNode</code> ("world" という単語を含む) はまだ存在しています。以下のコードは、 <code>myTextNode</code> を最近作成された <code><p></code> 要素である <code>myNewPTAGnode</code> に割り当てています。</p> + +<pre class="notranslate">myNewPTAGnode.appendChild(myTextNode); +</pre> + +<p>最終的に変更されたオブジェクトツリーはこのような状態なります。</p> + +<p><img alt="Image:sample2d.jpg" src="/@api/deki/files/837/=Sample2d.jpg"></p> + +<h2 id="Creating_a_table_dynamically_.28back_to_Sample1.html.29" name="Creating_a_table_dynamically_.28back_to_Sample1.html.29">表の動的生成 (Sample1.html に戻って)</h2> + +<p>この文書ではこれ以降再び sample1.html を扱っていきます。以下の図はこの例で生成される table オブジェクトツリー構造を表しています。</p> + +<h3 id="Reviewing_the_HTML_Table_structure" name="Reviewing_the_HTML_Table_structure">HTML 表構造の再確認</h3> + +<p><img alt="Image:sample1-tabledom.jpg" src="/@api/deki/files/833/=Sample1-tabledom.jpg"></p> + +<h3 id="Creating_element_nodes_and_inserting_them_into_the_document_tree" name="Creating_element_nodes_and_inserting_them_into_the_document_tree">要素ノードの生成とその文書ツリーへの挿入</h3> + +<p>sample1.html における基本的な table 生成の手順は次の通りです。</p> + +<ul> + <li>body オブジェクトを取得する (document オブジェクトの最初の項目)。</li> + <li>全ての要素を生成する。</li> + <li>最後に、各子供を (上の図のように) table 構造に従って付加していきます。以下のソースコードは sample1.html のコメント付き版になります。</li> +</ul> + +<div class="blockIndicator note"> +<p><code>start</code> 関数の最後には新たなコードがあります。 DOM のメソッド <code>setAttribute()</code> を用いて table の <code>border</code> プロパティが設定されており、 <code>setAttribute()</code> は属性名と属性値という 2 つの引数を取ります。 <code>setAttribute</code> メソッドを用いて任意の要素の任意の属性を設定することができます。</p> +</div> + +<pre class="brush: html; notranslate"><head> +<title>サンプルコード - 基本的 DOM インターフェイスによる HTML 要素の動的操作法</title> +<script> + function start() { + // body への参照を取得します + var mybody = document.getElementsByTagName("body")[0]; + + // <table> と <tbody> 要素を生成します + mytable = document.createElement("table"); + mytablebody = document.createElement("tbody"); + + // 全てのセルを生成します + for(var j = 0; j < 2; j++) { + // <tr> 要素を生成します + mycurrent_row = document.createElement("tr"); + + for(var i = 0; i < 2; i++) { + // <td> 要素を生成します + mycurrent_cell = document.createElement("td"); + // テキストノードを生成します + currenttext = document.createTextNode("cell is row " + j + ", column " + i); + // 生成したテキストノードを <td> セルへと付加します + mycurrent_cell.appendChild(currenttext); + // その <td> セルを <tr> 行へと付加します + mycurrent_row.appendChild(mycurrent_cell); + } + // その <tr> 行を <tbody> へと付加します + mytablebody.appendChild(mycurrent_row); + } + + // <tbody> を <table> へと付加します + mytable.appendChild(mytablebody); + // <table> を <body> へと付加します + mybody.appendChild(mytable); + // mytable の border 属性を 2 に設定します + mytable.setAttribute("border","2"); + } +</script> +</head> +<body onload="start()"> +</body> +</html></pre> + +<h2 id="Manipulating_the_table_with_DOM_and_CSS" name="Manipulating_the_table_with_DOM_and_CSS">DOM と CSS による表の操作</h2> + +<h3 id="Getting_a_text_node_from_the_table" name="Getting_a_text_node_from_the_table">表からのテキスト取得</h3> + +<p>この例では、2つの新しい DOM 属性を導入しています。まず、 <code>childNodes</code> 属性を使用して mycel の子ノードのリストを取得します。 <code>childNodes</code> リストには、名前やタイプに関係なく、すべての子ノードが含まれます。 <code>getElementsByTagName()</code> と同様に、ノードのリストを返します。</p> + +<p>違いは、(a) <code>getElementsByTagName()</code> が指定したタグ名の要素のみを返すことと、 (b) <code>getElementsByTagName()</code> が直系の子だけでなく、任意のレベルの子孫を返すことです。</p> + +<p>返されたリストを手に入れたら、 <code>[x]</code> メソッドを使って目的の子項目を取得します。この例では、表の2行目の2番目のセルのテキストノードを myceltext に格納しています。</p> + +<p>そして、この例では結果を表示するために、内容が <code>myceltext</code> のデータである新しいテキストノードを作成し、 <code><body></code> 要素の子として追加します。</p> + +<div class="blockIndicator note"> +<p>オブジェクトがテキストノードである場合、data 属性を使用して当該ノードのテキスト内容を得ることができます。</p> +</div> + +<pre class="brush: js; notranslate">mybody = document.getElementsByTagName("body")[0]; +mytable = mybody.getElementsByTagName("table")[0]; +mytablebody = mytable.getElementsByTagName("tbody")[0]; +myrow = mytablebody.getElementsByTagName("tr")[1]; +mycel = myrow.getElementsByTagName("td")[1]; + +// first item element of the childNodes list of mycel +myceltext=mycel.childNodes[0]; + +// currenttext の中身は myceltext の data 内容 +currenttext=document.createTextNode(myceltext.data); +mybody.appendChild(currenttext); +</pre> + +<h3 id="Getting_an_attribute_value" name="Getting_an_attribute_value">属性値の取得</h3> + +<p>sample1 の最後で <code>setAttribute</code> が <code>mytable</code> オブジェクトに対して呼び出されています。この呼び出しは table の border プロパティを設定するのに使用されています。属性をの値取得するには、属性オブジェクトを返す <code>getAttribute</code> メソッドを使用してください。</p> + +<pre class="brush: js; notranslate">mytable.getAttribute("border");</pre> + +<h3 id="Hiding_a_column_by_changing_style_properties" name="Hiding_a_column_by_changing_style_properties">スタイルプロパティ変更による列の非表示化</h3> + +<p>JavaScript 変数にオブジェクトを納めさえすれば、スタイルプロパティを直接設定できます。以下のコードは 2 列目の各セル非表示とされ 1 行目の各セルが赤い背景色を持つように変更された sample1.html です。style プロパティが直接設定されていることに注意して下さい。</p> + +<pre class="brush: html notranslate"><html> +<body onload="start()"> +</body> +<script> + function start() { + var mybody = document.getElementsByTagName("body")[0]; + mytable = document.createElement("table"); + mytablebody = document.createElement("tbody"); + + for(var row = 0; row < 2; row++) { + mycurrent_row=document.createElement("tr"); + for(var col = 0; col < 2; col++) { + mycurrent_cell = document.createElement("td"); + currenttext = document.createTextNode("cell is: " + row + col); + mycurrent_cell.appendChild(currenttext); + mycurrent_row.appendChild(mycurrent_cell); + // 0 列目であればセルの背景色を設定し、 + // 1 列目であればセルを非表示とする + if (col === 0) { + mycurrent_cell.style.background = "rgb(255,0,0)"; + } else { + mycurrent_cell.style.display = "none"; + } + } + mytablebody.appendChild(mycurrent_row); + } + mytable.appendChild(mytablebody); + mybody.appendChild(mytable); + } +</script> +</html></pre> + +<h4 id="Original_Document_Information" name="Original_Document_Information">出典情報</h4> + +<dl> + <dt>著者</dt> + <dd>Marcio Galli</dd> + <dt>引用元</dt> + <dd>http://web.archive.org/web/20000815054125/http://mozilla.org/docs/dom/technote/tn-dom-table/</dd> +</dl> diff --git a/files/ja/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html b/files/ja/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html new file mode 100644 index 0000000000..d9bc923da9 --- /dev/null +++ b/files/ja/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html @@ -0,0 +1,95 @@ +--- +title: W3C DOM Level 1 Core の使用 +slug: Web/API/Document_Object_Model/Using_the_W3C_DOM_Level_1_Core +tags: + - DOM + - NeedsUpdate +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core +--- +<div>{{DefaultAPISidebar("DOM")}}</div> + +<p>W3C の <a href="https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html">DOM Level 1 Core</a> は、 (他の文書のツリー風の型の中で) HTML や XML 文書の DOM ツリーを操作するための API です。 DOM は広く普及しているので、この API は Mozilla Firefox や Microsoft Internet Explorer、サーバーを含むすべての主要なブラウザーが対応しています。ウェブにおけるスクリプティングの未来を担う強力な基盤なのです。</p> + +<h2 id="What_is_a_content_tree.3F" name="What_is_a_content_tree.3F">DOM ツリーとは?</h2> + +<p><a href="https://www.w3.org/TR/REC-DOM-Level-1/introduction.html">DOM</a> ツリーは一種の <a href="https://en.wikipedia.org/wiki/Tree_structure">ツリー構造</a>で、ノードが HTML または XML 文書のコンテンツを表します。それぞれの HTML または XML 文書は固有の DOM ツリーの表現を持っています。例えば、以下の文書をご覧ください。</p> + +<pre class="brush: html notranslate"><html> +<head> + <title>My Document</title> +</head> +<body> + <h1>Header</h1> + <p>Paragraph</p> +</body> +</html> +</pre> + +<p>これは以下のように見える DOM ツリーを持っています。</p> + +<p><img alt="image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg" class="internal" src="/@api/deki/files/415/=Using_the_W3C_DOM_Level_1_Core-doctree.jpg"></p> + +<p>(なお、上位のツリーは上記の文書の DOM ツリーと似ていますが、同じではありません。<a href="/ja/docs/Web/API/Document_Object_Model/Whitespace_in_the_DOM">実際の DOM ツリーはホワイトスペースを温存するからです</a>。)</p> + +<p>ウェブブラウザーが HTML 文書を解釈するとき、ブラウザーは DOM ツリーを構築し、文書を表示するために使用します。</p> + +<h2 id="What_does_the_DOM_Level_1_Core_let_me_do.3F" name="What_does_the_DOM_Level_1_Core_let_me_do.3F">DOM Level 1 Core で何ができるの?</h2> + +<p>W3C DOM Level 1 Core によって<em>何でも好きな方法で</em> DOM ツリーを変更できます。これは、任意の HTML や XML 文書をゼロから作成したり、与えられた HTML や XML 文書の内容を変更したりすることができることを意味します。ウェブページの作者が文書の DOM を編集する最も簡単な方法は、 JavaScript を使ってグローバルオブジェクトの <code>document</code> プロパティにアクセスすることです。この <code>document</code> オブジェクトは、W3C の DOM Level 1 仕様の <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#i-Document">Document インターフェイス</a> を実装しています。</p> + +<h2 id="A_simple_example" name="A_simple_example">簡単な例</h2> + +<p>上の文書を元に作者は、ヘッダの内容を変え、1つある段落を 2 つに書き換えたいものとしましょう。これは以下のスクリプトによってできます。</p> + +<h3 id="HTML_Content" name="HTML_Content">HTML コンテンツ</h3> + +<pre class="brush: html notranslate"><body> +<input type="button" value="Change this document." onclick="change()"> +<h2>Header</h2> +<p>Paragraph</p> +</body><span> +</span></pre> + +<h3 id="JavaScript_Content" name="JavaScript_Content">JavaScript コンテンツ</h3> + +<pre class="brush: js notranslate"><span> function change() { + // document.getElementsByTagName("H2") は、文書内の <h2> 要素の NodeList + // であり、最初のものは0番です。 + + var header = document.getElementsByTagName("H2").item(0); + // header の firstChild はテキストノードです。 + header.firstChild.data = "A dynamic document"; + // ヘッダーが "A dynamic document" になりました。 + + var para = document.getElementsByTagName("P").item(0); + para.firstChild.data = "This is the first paragraph."; + + // 第二の段落のために新しいテキストノードを生成します + var newText = document.createTextNode("This is the second paragraph."); + // 第二の段落になる新しい Element を生成します + var newElement = document.createElement("P"); + // 段落にテキストを置きます + newElement.appendChild(newText); + // また、 (段落の親に当たる) BODY に追加することで、文書の最後に + // 段落を置きます + para.parentNode.appendChild(newElement); + }</span></pre> + +<p>{{ EmbedLiveSample('A_simple_example', 800, 300) }}</p> + +<p>このスクリプトを<a class="internal" href="/@api/deki/files/2866/=example.html">完全なデモ</a>として見ることができます。</p> + +<h2 id="How_can_I_learn_more.3F" name="How_can_I_learn_more.3F">どうすればもっと学べるの?</h2> + +<p>DOM の基本概念に親しんでもらいましたが、 <a href="/ja/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces">DOM Level 1 の基本的なメソッド</a>について学習したくなるかもしれません。</p> + +<p>W3C の <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html">DOM Level 1 Core 仕様書</a> も参照して下さい。公式仕様ではありますが結構読みやすいです。特に各 DOM オブジェクトとその全プロパティ及びメソッドの説明が役立ちます。<a href="/ja/docs/Web/API/Document_Object_Model">その他の DOM 関連文書</a> も参照して下さい。</p> + +<div class="originaldocinfo"> +<p><strong>原著情報</strong></p> + +<ul> + <li>著者: L. David Baron <dbaron at dbaron dot org></li> + <li>著作権情報: © 1998-2005 by individual mozilla.org contributors; content available under a <a class="external" href="http://www.mozilla.org/foundation/licensing/website-content.html">Creative Commons license</a></li> +</ul> +</div> diff --git a/files/ja/web/api/document_object_model/whitespace/index.html b/files/ja/web/api/document_object_model/whitespace/index.html new file mode 100644 index 0000000000..c6c3aa5d48 --- /dev/null +++ b/files/ja/web/api/document_object_model/whitespace/index.html @@ -0,0 +1,468 @@ +--- +title: ホワイトスペースは HTML、 CSS、そして DOM 内でどう扱われるか +slug: Web/API/Document_Object_Model/Whitespace +tags: + - CSS + - DOM + - HTML + - JavaScript + - whitespace +translation_of: Web/API/Document_Object_Model/Whitespace +--- +<div>{{APIRef("DOM")}}</div> + +<p><a href="/ja/docs/Web/API/Document_Object_Model">DOM</a> にホワイトスペースが存在すると、レイアウトの問題が発生したり、ホワイトスペースがある場所によっては、予期せぬ方法でコンテンツツリーの操作が困難になることがあります。この記事では、どのような場合に問題が発生するかを探り、その結果生じる問題を軽減するために何ができるかを見ていきます。</p> + +<h2 id="What_is_whitespace" name="What_is_whitespace">ホワイトスペースとは</h2> + +<p>ホワイトスペースとは、スペース、タブ、改行 (正確には、CRLF シーケンス、キャリッジリターン、改行) のみで構成されたテキストの文字列のことです。これらの文字を使用することで、自分や他の人が読みやすいようにコードを整形することができます。実際、私たちのソースコードの多くはこれらのホワイトスペースであふれており、コードのダウンロードサイズを減らすために、本番のビルド段階でホワイトスペースを取り除く傾向があります。</p> + +<h3 id="HTML_largely_ignores_whitespace" name="HTML_largely_ignores_whitespace">HTML は大体空白を無視するのか</h3> + +<p>HTML の場合、ホワイトスペースはほとんど無視されます。単語と単語の間のホワイトスペースは 1文字として扱われ、要素の開始と終了、要素外のホワイトスペースは無視されます。以下の最小限の例を見てみましょう。</p> + +<pre class="brush: html"><!DOCTYPE html> + + <h1> Hello World! </h1></pre> + +<p>このソースコードには、<code>DOCTYPE</code> の後に 2 つの改行と <code><h1></code> 要素の前後と内部に空白文字の束が含まれていますが、ブラウザーは全く気にしていないようで、これらの文字が全く存在しないかのように "Hello World!" という言葉を表示しています。</p> + +<p>{{EmbedLiveSample('HTML_largely_ignores_whitespace')}}</p> + +<p>これは、ホワイトスペースがページのレイアウトに影響を与えないようにするためです。要素の周囲や内部に余白を作るのは CSS の仕事です。</p> + +<h3 id="What_does_happen_to_whitespace" name="What_does_happen_to_whitespace">ホワイトスペースに 何が<em>起こる</em>のか</h3> + +<p>しかし、ただ消えるだけではありません。</p> + +<p>元の文書で HTML 要素の外にあるホワイトスペースはすべて DOM で表現されます。これは、エディターが文書の書式を保持するために内部的に必要です。これは、次のことを意味します。</p> + +<ul> + <li>ホワイトスペースのみを含むテキストノードが存在し、</li> + <li>テキストノードによっては先頭や末尾にホワイトスペースを持つことがある。</li> +</ul> + +<p>例えば、次の文書を見てください。</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> +<head> + <title>My Document</title> +</head> +<body> + <h1>Header</h1> + <p> + Paragraph + </p> +</body> +</html> +</pre> + +<p>この DOM ツリーは次のように見えます。</p> + +<p><img alt="上記の HTML の例と同等の DOM ツリー" src="https://mdn.mozillademos.org/files/17084/dom-string.png" style="display: block; height: 288px; margin: 0 auto; width: 562px;"></p> + +<p>DOM でホワイトスペースを保存することは多くの点で便利ですが、特定のレイアウトを実装するのが難しくなったり、DOM 内のノードを反復処理したい開発者にとっては問題が生じたりする場所があります。これらの問題と解決策については、後ほど見ていきましょう。</p> + +<h3 id="How_does_CSS_process_whitespace" name="How_does_CSS_process_whitespace">CSS はホワイトスペースをどのように処理するのか</h3> + +<p>ほとんどのホワイトスペースは無視されますが、すべてが無視されるわけではありません。先ほどの例では、"Hello" と "World!" の間のホワイトスペースの一つは、ブラウザーでページがレンダリングされたときにまだ存在しています。ブラウザーエンジンには、どのホワイトスペースが有用でどれが不要かを決定する規則があります — これらは、少なくとも <a href="https://www.w3.org/TR/css-text-3">CSS テキストモジュールレベル 3</a>、特に <a href="https://www.w3.org/TR/css-text-3/#white-space-property">CSS の white-space プロパティ</a>と<a href="https://www.w3.org/TR/css-text-3/#white-space-processing">ホワイトスペースの処理の詳細</a>についての部分で規定されていますが、以下ではより簡単な説明を提供します。</p> + +<p>もう一つ、本当に簡単な例を挙げてみましょう。簡単にするように、すべての空白を ◦ で、すべてのタブを ⇥ で、すべての開業を ⏎ で表現します。</p> + +<p>例を示します。</p> + +<pre class="brush: html"><h1>◦◦◦Hello◦⏎ +⇥⇥⇥⇥<span>◦World!</span>⇥◦◦</h1></pre> + +<p>これはブラウザーで次のようにレンダリングされます。</p> + +<div class="hidden"> +<h4 id="Hidden_example" name="Hidden_example">Hidden example</h4> + +<pre class="brush: html"><h1> Hello + <span> World!</span> </h1></pre> +</div> + +<p>{{EmbedLiveSample('Hidden_example')}}</p> + +<p><code><h1></code> 要素はインライン要素のみを含んでいます。実際にはこのようなものを含んでいます。</p> + +<ul> + <li>1 つのテキストノード (いくつかの空白、"Hello" という語、いくつかのタブから成る)</li> + <li>1 つのインライン要素 (<code><span></code> で、中に空白と "World!" という語を含む)</li> + <li>もう 1 つのテキストノード (タブと空白のみから成る)</li> +</ul> + +<p>このため、<a href="/ja/docs/Web/CSS/Inline_formatting_context">インライン整形コンテキスト</a>と呼ばれるものを確立します。これは、ブラウザーエンジンが作業を行う存在する可能性のあるレイアウトレンダリングコンテキストの一つです。</p> + +<p>このコンテキストの中では、ホワイトスペース文字の処理は次のように要約されます。</p> + +<ol> + <li> + <p>まず、改行の直前と直後の空白とタブはすべて無視されるので、以前のマークアップの例を参考にして、この最初の規則を適用すると、次のようになります。</p> + + <pre class="brush: html"><h1>◦◦◦Hello⏎ +<span>◦World!</span>⇥◦◦</h1></pre> + </li> + <li> + <p>次に、タブ文字がすべて空白として扱われるので、この例は次のようになります。</p> + + <pre class="brush: html"><h1>◦◦◦Hello⏎ +<span>◦World!</span>◦◦◦</h1></pre> + </li> + <li> + <p>次に、改行が空白に変換されます。</p> + + <pre class="brush: html"><h1>◦◦◦Hello◦<span>◦World!</span>◦◦◦</h1></pre> + </li> + <li> + <p>その後で、空白の直後に他の空白がある場合は (2 つが別々なインライン要素をまたぐ場合も含めて) 無視されるので、次のようになります。</p> + + <pre class="brush: html"><h1>◦Hello◦<span>World!</span>◦</h1></pre> + </li> + <li> + <p>そして、行頭と行末の一連の空白が削除されるので、ようやくこんな感じになります。</p> + + <pre class="brush: html"><h1>Hello◦<span>World!</span></h1></pre> + </li> +</ol> + +<p>このため、ウェブページを訪れた人は、ひどく字下げされた "Hello" に続いてもっとひどく字下げされた "World!" をその下の行に見かけるのではなく、ページの先頭にきれいに書かれた "Hello World!" という文言を見ることになります。</p> + +<div class="blockIndicator note"> +<p><strong>メモ</strong>: <a href="/ja/docs/Tools">Firefox DevTools</a> ではバージョン 52 以降、テキストノードの強調表示に対応しており、どのノードにホワイトスペース文字が含まれているかを正確に確認できるようになりました。純粋なホワイトスペースノードには "whitespace" ラベルが付けられます。</p> +</div> + +<h3 id="Whitespace_in_block_formatting_contexts" name="Whitespace_in_block_formatting_contexts">ブロック整形コンテキストでのホワイトスペース</h3> + +<p>Above we just looked at elements that contain inline elements, and inline formatting contexts. If an element contains at least one block element, then it instead establishes what is called a <a href="/ja/docs/Web/Guide/CSS/Block_formatting_context">block formatting context</a>.</p> + +<p>Within this context, whitespace is treated very differently. Let’s take a look at an example to explain how. We've marked the whitespace characters as before.</p> + +<pre class="brush: html"><body>⏎ +⇥<div>◦◦Hello◦◦</div>⏎ +⏎ +◦◦◦<div>◦◦World!◦◦</div>◦◦⏎ +</body></pre> + +<p>We have 3 text nodes that contain only whitespace, one before the first <code><div></code>, one between the 2 <code><divs></code>, and one after the second <code><div></code>.</p> + +<p>This renders like so:</p> + +<div class="hidden"> +<h4 id="Hidden_example_2" name="Hidden_example_2">Hidden example 2</h4> + +<pre class="brush: html"><body> + <div> Hello </div> + + <div> World! </div> +</body></pre> +</div> + +<p>{{EmbedLiveSample('Hidden_example_2')}}</p> + +<p>We can summarize how the whitespace here is handled as follows (the may be some slight differences in exact behavior between browsers, but this basically works):</p> + +<ol> + <li> + <p>Because we’re inside a block formatting context, everything must be a block, so our 3 text nodes also become blocks, just like the 2 <code><div></code>s. Blocks occupy the full width available and are stacked on top of each other, which means that we end up with a layout composed of this list of blocks:</p> + + <pre class="brush: html"><block>⏎⇥</block> +<block>◦◦Hello◦◦</block> +<block>⏎◦◦◦</block> +<block>◦◦World!◦◦</block> +<block>◦◦⏎</block></pre> + </li> + <li> + <p>This is then simplified further by applying the processing rules for whitespace in inline formatting contexts to these blocks:</p> + + <pre class="brush: html"><block></block> +<block>Hello</block> +<block></block> +<block>World!</block> +<block></block></pre> + </li> + <li> + <p>The 3 empty blocks we now have are not going to occupy any space in the final layout, because they don’t contain anything, so we’ll end up with only 2 blocks taking up space in the page. People viewing the web page see the words "Hello" and "World!" on 2 separate lines as you’d expect 2 <code><div></code>s to be laid out. The browser engine has essentially ignored all of the whitespace that was added in the source code.</p> + </li> +</ol> + +<h2 id="Spaces_in_between_inline_and_inline-block_elements" name="Spaces_in_between_inline_and_inline-block_elements">inline および inline-block 要素間の空白</h2> + +<p>Let's move on to look at a few issues that can arise due to whitespace, and what can be done about them. First of all, we'll look at what happens with spaces in between inline and inline-block elements. In fact, we saw this already in our very first example, when we described how whitespace is processed inside inline formatting contexts.</p> + +<p>We said that there were rules to ignore most characters but that word-separating characters remain. When you’re only dealing with block-level elements such as <code><p></code> that only contain inline elements such as <code><em></code>, <code><strong></code>, <code><span></code>, etc., you don’t normally care about this because the extra whitespace that does make it to the layout is helpful to separate the words in the sentence.</p> + +<p>It gets more interesting however when you start using <code>inline-block</code> elements. These elements behave like inline elements on the outside, and blocks on the inside, and are often used to display more complex pieces of UI than just text, side-by-side on the same line, for example navigation menu items.</p> + +<p>Because they are blocks, many people expect that they will behave as such, but really they don’t. If there is formatting whitespace between adjacent inline elements, this will result in space in the layout, just like the spaces between words in text.</p> + +<p>Consider this example (again, the whitespace characters in the HTML are marked so they are visible):</p> + +<pre class="brush: css" id="ef6f">.people-list { + list-style-type: none; + margin: 0; + padding: 0; +} + +.people-list li { + display: inline-block; + width: 2em; + height: 2em; + background: #f06; + border: 1px solid; +} +</pre> + +<pre class="brush: html" id="24bb"><ul class="people-list">⏎ + +◦◦<li></li>⏎ + +◦◦<li></li>⏎ + +◦◦<li></li>⏎ + +◦◦<li></li>⏎ + +◦◦<li></li>⏎ + +</ul></pre> + +<p>This renders as follows:</p> + +<div class="hidden"> +<h3 id="Hidden_example_3" name="Hidden_example_3">Hidden example 3</h3> + +<pre class="brush: css" id="ef6f">.people-list { list-style-type: none; margin: 0; padding: 0; } +.people-list li { display: inline-block; width: 2em; height: 2em; background: #f06; border: 1px solid; } +</pre> + +<pre class="brush: html" id="24bb"><ul class="people-list"> + + <li></li> + + <li></li> + + <li></li> + + <li></li> + + <li></li> + +</ul></pre> +</div> + +<p>{{EmbedLiveSample('Hidden_example_3')}}</p> + +<p>You probably don't want the gaps in between the blocks — depending on the use case (is this a list of avatars, or horizontal nav buttons?), you probably want the element sides flush with each other, and to be able to control any spacing yourself.</p> + +<p>The Firefox DevTools HTML Inspector will highlight text nodes, and also show you exactly what area the elements are taking up — useful if you are wondering what is causing the problem, and are maybe thinking you've got some extra margin in there or something!</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/17085/whitespace-devtools.png" style="border-style: solid; border-width: 1px; height: 454px; width: 797px;"></p> + +<p>There are a few ways of getting around this problem:</p> + +<p>Use <a href="/ja/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a> to create the horizontal list of items instead of trying an <code>inline-block</code> solution. This handles everything for you, and is definitely the preferred solution:</p> + +<pre class="brush: css">ul { + list-style-type: none; + margin: 0; + padding: 0; + display: flex; +}</pre> + +<p>If you need to rely on <code>inline-block</code>, you could set the <code><a href="/ja/docs/Web/CSS/font-size">font-size</a></code> of the list to 0. This only works if your blocks are not sized with ems (based on the <code>font-size</code>, so the block size would also end up being 0). rems would be a good choice here:</p> + +<pre class="brush: css">ul { + font-size: 0; + ... +} + +li { + display: inline-block; + width: 2rem; + height: 2rem; + ... +} +</pre> + +<p>Or you could set negative margin on the list items:</p> + +<pre class="brush: css">li { + display: inline-block; + width: 2rem; + height: 2rem; + margin-right: -0.25rem; +}</pre> + +<p>You can also solve this problem by putting your list items all on the same line in the source, which causes the whitespace nodes to not be created in the first place:</p> + +<pre class="brush: html"><li></li><li></li><li></li><li></li><li></li></pre> + +<h2 id="DOM_traversal_and_whitespace" name="DOM_traversal_and_whitespace">DOM トラバーサルとホワイトスペース</h2> + +<p>When trying to do <a href="/ja/docs/Web/API/Document_Object_Model">DOM</a> manipulation in JavaScript, you can also encounter problems because of whitespace nodes. For example, if you have a reference to a parent node and want to affect its first element child using <code><a href="/ja/docs/Web/API/Node/firstChild">Node.firstChild</a></code>, if there is a rogue whitespace node just after the opening parent tag you will not get the result you are expecting. The text node would be selected instead of the element you want to affect.</p> + +<p>As another example, if you have a certain subset of elements that you want to do something to based on whether they are empty (have no child nodes) or not, you could check whether each element is empty using something like <code><a href="/ja/docs/Web/API/Node/hasChildNodes">Node.hasChildNodes()</a></code>, but again, if any target elements contain text nodes, you could end up with false results.</p> + +<h2 id="Whitespace_helper_functions" name="Whitespace_helper_functions">ホワイトスペースヘルパー関数</h2> + +<p>The JavaScript code below defines several functions that make it easier to deal with whitespace in the DOM:</p> + +<pre class="brush:js">/** + * スクリプト全体で、ホワイトスペースを以下のいずれかの文字として定義しています。 + * "\t" TAB \u0009 + * "\n" LF \u000A + * "\r" CR \u000D + * " " SPC \u0020 + * + * JavaScript の \s は非改行スペース (および他のいくつかの文字) を含んでいる為 + * このスクリプトでは使用しません。 + */ + + +/** + * ノードのテキスト内容が完全に空白であるか判断 + * + * @param nod CharacterData インターフェイスを実装したノード + * (例: Text, Comment, CDATASection ノード) + * @return nod のテキスト内容がすべてホワイトスペースであれば true + * それ以外は false + */ +function is_all_ws( nod ) +{ + // ECMA-262 第3版 の String および RegExp の機能を使用 + return !(/[^\t\n\r ]/.test(nod.data)); +} + + +/** + * 反復処理関数がノードを無視するべきかどうか判断 + * + * @param nod DOM1 の Node インターフェイスを実装したノード + * @return ノードが次のいずれかであれば true: + * 1) すべてホワイトスペースである Text ノード + * 2) Comment ノード + * それ以外は false + */ + +function is_ignorable( nod ) +{ + return ( nod.nodeType == 8) || // コメントノード + ( (nod.nodeType == 3) && is_all_ws(nod) ); // 全空白テキストノード +} + +/** + * 完全に空白あるいはコメントのノードを無視するようにした previousSibling + * (通常 previousSibling はすべての DOM ノードが持つプロパティのことで、親が + * 同じで参照ノードの直前にある兄弟ノードを表します) + * + * @param sib 参照ノード + * @return 次のいずれか: + * 1) is_ignorable 検査で無視できないと判断された sib に + * 最も近い前方の兄弟ノード、あるいは + * 2) 該当するノードがなければ null + */ +function node_before( sib ) +{ + while ((sib = sib.previousSibling)) { + if (!is_ignorable(sib)) return sib; + } + return null; +} + +/** + * 完全に空白あるいはコメントのノードを無視するようにした nextSibling + * + * @param sib 参照ノード + * @return 次のいずれか: + * 1) is_ignorable 検査で無視できないと判断された sib に + * 最も近い後方の兄弟ノード、あるいは + * 2) 該当するノードがなければ null + */ +function node_after( sib ) +{ + while ((sib = sib.nextSibling)) { + if (!is_ignorable(sib)) return sib; + } + return null; +} + +/** + * 完全に空白あるいはコメントのノードを無視するようにした lastChild + * (通常 lastChild はすべての DOM ノードが持つプロパティのことで、参照ノードに + * 直接含まれる最後のノードを表します) + * + * @param sib 参照ノード + * @return 次のいずれか: + * 1) is_ignorable 検査で無視できないと判断された sib の + * 最後の子供ノード、あるいは + * 2) 該当するノードがなければ null + */ +function last_child( par ) +{ + var res=par.lastChild; + while (res) { + if (!is_ignorable(res)) return res; + res = res.previousSibling; + } + return null; +} + +/** + * 完全に空白あるいはコメントのノードを無視するようにした firstChild + * + * @param sib 参照ノード + * @return 次のいずれか: + * 1) is_ignorable 検査で無視できないと判断された sib の + * 最初の子供ノード、あるいは + * 2) 該当するノードがなければ null + */ +function first_child( par ) +{ + var res=par.firstChild; + while (res) { + if (!is_ignorable(res)) return res; + res = res.nextSibling; + } + return null; +} + +/** + * 最初と最後にホワイトスペースを含まず、すべてのホワイトスペースを単一スペースに正規化する + * ようにした data + * (通常 data はテキストノードが持つプロパティのことで、ノードのテキストを + * 表します) + * + * @param txt data が返されるべきテキストノード + * @return 当該テキストノードの内容が与えるホワイトスペースを纏めた文字列 + */ +function data_of( txt ) +{ + var data = txt.data; + // ECMA-262 第3版 の String および RegExp の機能を使用 + data = data.replace(/[\t\n\r ]+/g, " "); + if (data.charAt(0) == " ") + data = data.substring(1, data.length); + if (data.charAt(data.length - 1) == " ") + data = data.substring(0, data.length - 1); + return data; +} +</pre> + +<h2 id="Example" name="Example">例</h2> + +<p>The following code demonstrates the use of the functions above. It iterates over the children of an element (whose children are all elements) to find the one whose text is <code>"This is the third paragraph"</code>, and then changes the class attribute and the contents of that paragraph.</p> + +<pre class="brush: js">var cur = first_child(document.getElementById("test")); +while (cur) +{ + if (data_of(cur.firstChild) == "This is the third paragraph.") + { + cur.className = "magic"; + cur.firstChild.textContent = "This is the magic paragraph."; + } + cur = node_after(cur); +} +</pre> |
