1. 要素をタグ名で取得
JavaScript で要素をタグ名で取得するには、
getElementsByTagName メソッド
を用いる。
例えば、HTML の div 要素を取得するには、
document.getElementsByTagname("div");
ちなみに、getElementsByTagName メソッドの Elements の `s’ をよく忘れ、エラーになることがある。 (+_+)
このメソッドは、Document インターフェイスで定義されている。
The
Documentinterface represents the entire HTML or XML document. …
getElementsByTagNameReturns a
NodeListof all theElementswith a given tag name in the order in which they are encountered in a preorder traversal of theDocumenttree.Parameters
tagnameof typeDOMString- The name of the tag to match on. The special value "*" matches all tags.
Return Value
インデックスで要素にアクセスする
getElementsByTagName によって返されるオブジェクトは NodeList 。
getElementsByTagNameReturns a
NodeListof all theElementswith a given tag name in the order in which they are encountered in a preorder traversal of theDocumenttree.
NodeList は、配列のようにインデックスで要素にアクセスできる。
The
NodeListinterface provides the abstraction of an ordered collection of nodes, …The items in the
NodeListare accessible via an integral index, starting from 0.
div 要素の 0 番目の要素を取得するには、
document.getElementsByTagname("div")[0];
2. テキストの内容を表示
要素を取得したら、その内容を表示したい。そのためには、Node オブジェクトに定義されている textContent 属性を取得する。
textContet は Document Object Model Core の Interface Node に定義されている。
textContentof typeDOMString, introduced in DOM Level 3This attribute returns the text content of this node and its descendants.
div 要素の 0 番目の要素のテキストを取得するには、
document.getElementsByTagname("div")[0].textContent;
0コメント:
コメントを投稿