Warning: Undefined array key 0 in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/functions.php on line 406

Warning: Attempt to read property "parent" on null in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/functions.php on line 407

Warning: Attempt to read property "term_id" on null in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/functions.php on line 413

Warning: Attempt to read property "cat_name" on null in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/functions.php on line 413

JavaScriptのDOM


Warning: Undefined variable $pre in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/functions.php on line 517
JavaScript

JavaScriptからHTMLやCSSに干渉し、静的なページに動的な動作を持たせることができます。 例として下の「背景色を変更」をクリックすると、背景色がランダムに変わります。

#sample{ border:solid 1px #000; margin:24px 0; } #sample button{ border: 2px solid #FFF; background-color:silver; border-radius: 4px; margin:4px; padding: 4px; display:block; } function chgcolor(){ var color = “#” + Math.floor(Math.random() * 0xFFFFFF).toString(16); document.getElementById(‘sample’).style.backgroundColor=color; }

このような処理には「DOM(Document Object Model)」という仕組みを使っています。 HTML文書をオブジェクトとして捉え、トップレベルの要素を「document」として要素やセレクタを指定して干渉するのです。

ソースはこのようになっています。

  function chgcolor(){
    var color = "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16);
    document.getElementById('sample').style.backgroundColor=color;
  }


<div id="sample">
  <button>背景色の変更</button>
</div>

代表的なDOMAPIメソッドを以下にいくつか紹介します。 これらメソッドを利用すれば本来静的であるHTML文書を書き換えて、まるで動的なページであるかのように動かせるのです。

メソッド取得方法利用できるノード
getElementById(id)idを属性値に持つ要素の検索document
getElementByTagName(tag)タグ名「tag」の要素を検索document、任意のエレメントノード
getElementByClassName(className)classNameをclass属性地に含む要素を検索document、任意のエレメントノード
getElementByName(name)nameをname属性地に持つ要素すべて検索document
querySelector(selector)selectornoCSSセレクタにマッチする要素の1つ目を検索document、任意のエレメントノード
querySelectorAll(selector)selectornoCSSセレクタにマッチする要素全て検索document、任意のエレメントノード
createElement(tag)新たなエレメントノードを作るdocument
appendChild(element)elementを自身の子要素としてDOMツリーに加える任意のエレメントノード

Warning: Undefined variable $category in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/content.php on line 79

Warning: Attempt to read property "name" on null in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/content.php on line 79

の記事

eyecatch

windows環境でファイルの拡張子を表示させる方法

eyecatch

改行・空白・タブ

eyecatch

サイトのPV数を増やす3つの基本

eyecatch

WordPressのインストール後にやっておくべき設定

eyecatch

CSSで指定したスタイルをHTMLに読み込む方法

eyecatch

ファイルの作成方法


Warning: Undefined variable $category in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/content.php on line 84

Warning: Attempt to read property "count" on null in /home/yatsuba/yatsuba.com/public_html/wp-content/themes/amaru/content.php on line 84
HOME