TypeScriptでDOM要素を作成する

TypeScriptでDOM要素を作成する

Angularが公式にサポートしている言語はTypeScriptなので、TypeScriptでDOMの操作をしてみます。JSと変わりありませんが、型(インタフェース名)は意識する必要があります。

ということで色々なDOMを作成するコードを書いてみました。

HTMLButtonElement

const button:HTMLButtonElement = <HTMLButtonElement>document.createElement('button');
button.textContent = "ボタン";
button.onclick = function() {
  alert('yes');
}
document.body.appendChild(button);

HTMLInputElement

const input:HTMLInputElement = <HTMLInputElement>document.createElement('input');
input.type = "text"; // checkboxなども指定可能
input.value = "ボタン";
input.onclick = function() {
alert('yes');
}

document.body.appendChild(input);

HTMLDivElement

const input:HTMLDivElement = <HTMLDivElement>document.createElement('div');
input.textContent = "div内です";
input.style.color = "red";
input.onclick = function() {
  alert('yes');
}

document.body.appendChild(input);

HTMLAnchorElement

const input:HTMLAnchorElement = <HTMLAnchorElement>document.createElement('a');
input.href = "https://www.yahoo.co.jp/";
input.textContent = "アンカータグです";
input.style.color = "red";

document.body.appendChild(input);

HTMLParagraphElement

const input:HTMLParagraphElement = <HTMLParagraphElement>document.createElement('p');
input.textContent = "pタグです";
input.style.color = "red";
input.onclick = function() {
  alert('yes');
}
document.body.appendChild(input);

HTMLElementとは

HTMLElementは、各DOMのinterfaceになります。

lib.dom.tsを見ればわかりますが、以下のようになっていると思います。

interface HTMLInputElement extends HTMLElement {

各DOMのinterfaceを合わせてくれるインターフェースになります。

MouseEvent(onclick)

MouseEventは、clickイベントやmouseover時のコールバック関数の第一引数の型(インタフェース)になります。

const input:HTMLInputElement = <HTMLInputElement>document.createElement('input');
input.type = "text";
input.value = "ボタン";
input.onclick = function(event:MouseEvent) { // ここ
  alert(event);
}
document.body.appendChild(input);

MouseEvent(onmouseover)

const input:HTMLInputElement = document.createElement('input');
input.type = "text";
input.value = "ボタン";
input.onmouseover = function(event:MouseEvent) { // ここ
  alert(event);
}
document.body.appendChild(input);

HTMLFormElement(submit)

const form:HTMLFormElement = document.createElement('form');
form.type = "text";
form.value = "ボタン";
form.submit();
document.body.appendChild(form);

コメント

タイトルとURLをコピーしました