JavaScript 備忘録

ドキュメントオブジェクトを操作するモデルをDOM(Document Object Model)と呼びます。
JavaScriptでは、オブジェクトのメンバーをプロパティと呼びます。Javaのフィールドやメソッドに対応します。
Window Object Properties & Window Object Methods

 


 

index.html

<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>hello</title>
<link type="text/css" rel="stylesheet" href="./css/style.css">
</head>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="./js/module.js" charset="utf-8"></script>
<!-- コメント -->
</body>
</html>
 

表示

F12を押せば、console画面が表示される。

 

write.html

<html>
<body>
<script>
alert("Hello!");
console.log("Hello!");
document.write("Hello!" + "<br>");
document.body.innerHTML += "Hello!" + "<br>";
document.body.insertAdjacentHTML("afterbegin", "aaaaa" + "<br>");
document.body.insertAdjacentHTML("beforeend", "zzzzz" + "<br>");
</script>
</body>
</html>
 

createElement

classを設定するときは、classNameを使いこと!setAttribute()は使うな!

 

createElement.html

<html>
<body>
<script>
var button = document.createElement("button");
button.id = "OK";
button.innerHTML = "OK";
button.onclick = function () {$click();};
/*
button.addEventListener("click", function () {
  document.querySelector("#output").innerHTML = document.querySelector("#input").value;
});
*/
document.body.appendChild(button);
var input = document.createElement("input");
input.id = "input";
input.type = "text";
input.className = "xxxxx";
document.body.appendChild(input);
var output = document.createElement("output");
output.id = "output";
document.body.appendChild(output);
function $click() {
  document.querySelector("#output").innerHTML = document.querySelector("#input").value;
}
</script>
</body>
</html>
 

createTextNode

 

createTextNode.html

<html>
<body>
<script>
var h1 = document.createElement("h1");
var textNode = document.createTextNode("Hello!");
document.body.appendChild(h1);
h1.appendChild(textNode);
</script>
</body>
</html>
 

要素の選択

children
childNodes
parentNode
firstElementChild
lastElementChild

getElementById("id")
getElementsByName("name")[0](ブラウザごとに動作が異なる場合がある)
getElementsByTagName("tag")[0]
getElementsByClassName("class")[0]

querySelector("#id .class input[type='text']")
querySelectorAll("#id .class input[type='text']")[0]

$(".class").eq(0)
$("#id").find(".class").eq(0)

注)jQueryで使える :checkbox、:radio、:checked などのセレクタをquerySelectorで使うとエラーになります。IE以外のブラウザはサポートしています。

 

getElementById.html

<html>
<body>
<form>
<input type="text" id="text1">
<input type="text" id="text2">
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
document.getElementById("text1").value = "Hello1!";
document.body.insertAdjacentHTML("beforeend", document.getElementById("text1").value);
$("#text2").val("Hello2!");
document.body.insertAdjacentHTML("beforeend", $("#text2").val());
</script>
</body>
</html>
 

テキストノードの読み・書き

 

text.html

<html>
<body>
<div id="div1"><p>Hello1!</p></div>
<div id="div2"><p>Hello2!</p></div>
<div id="div3"><p>Hello3!</p></div>
<div id="div4"></div>
<div id="div5"></div>
<script>
document.querySelector("#div1").innerHTML += "<p>Goodbye1!</p>";
document.querySelector("#div2").innerText += "<p>Goodbye2!</p>"; //非推奨
document.querySelector("#div3").textContent += "<p>Goodbye3!</p>";
document.querySelector("#div4").innerHTML = document.querySelector("#div1").textContent;
document.querySelector("#div5").textContent = document.querySelector("#div1").innerHTML;
</script>
</body>
</html>
 

エレメントノードの追加・削除

children → エレメント
childNodes → ノード(エレメント、テキスト)

 

element.html

<html>
<body>
<script>
var div = document.createElement("div");
div.innerHTML = "<p>Hello!</p>";
document.body.appendChild(div);
document.body.removeChild(div);
//document.body.removeChild(document.body.children[1]);
//div.remove();
document.body.innerHTML += document.body.children[0].tagName;

/*
element0.appendChild(element1);
element0.removeChild(element1);
element.parentNode.removeChild(element);
element.removeChild(element.children[0]);
while (element.children[0]) element.removeChild(element.children[0]);
element.remove();(IE:×)
*/

</script>
</body>
</html>
 

input要素

 

input.html

<html>
<body>
<button onclick="writeOK('#input');">書き込みOK</button>
<button onclick="writeNG('#input');">書き込みNG</button>
<input type="text" id="input" placeholder="入力してください!" readonly>
<input type="search" name="key">
<input type="submit" name="key" value="送信">
<input type="password" value="xxxxxxxxxx">
<input type="time" value="00:00:00">
<script>
function writeOK(id) {
  document.querySelector(id).readOnly = false;
}
function writeNG(id) {
  document.querySelector(id).readOnly = true;
}
</script>
</body>
</html>
 

textarea要素

 

textarea.html

<html>
<body>
<textarea cols="50" rows="10" placeholder="input"></textarea>
</body>
</html>
 

onclick

 

onclick.html

<html>
<body>
<input type="button" value="OK" onclick="$echo('#input', '#output');">
<input type="text" id="input">
<output id="output"></output>
<script>
function $echo(input, output) {
  document.querySelector(output).innerHTML += document.querySelector(input).value;
}
</script>
</body>
</html>
 

onchange

 

onchange.html

<html>
<body>
<input type="checkbox" onchange="$echo('#input', '#output');">
<input type="text" id="input">
<output id="output"></output>
<script>
function $echo(input, output) {
  document.querySelector(output).innerHTML += document.querySelector(input).value;
}
</script>
</body>
</html>
 

value属性の読み書き

 

value.html

<html>
<body>
<input type="text" id="input1">
<input type="hidden" id="input2">
<script>
document.querySelector("#input1").value = "abcde1";
document.querySelector("#input2").value = "abcde2";
document.body.insertAdjacentHTML("beforeend", document.querySelector("#input1").value);
document.body.insertAdjacentHTML("beforeend", document.querySelector("#input2").value);
</script>
</body>
</html>
 

 

value.html

<html>
<body>
<div id="div">
****************************************************************************************************
</div>
<data id="data">abcde</data>
aaaaaaaaaazzzzzzzzzz
<br><br><br><br><br>
<script>
document.querySelector("#data").value = document.querySelector("#div").textContent;
document.body.innerHTML += document.querySelector("#data").value + "<br>";
document.body.insertAdjacentHTML("beforeend", document.querySelector("#data").value + "<br>");
</script>
</body>
</html>
 

JSON.parse() と JSON.stringify()

JSON.parse():JSON(文字列) → JavaScriptのオブジェクト
JSON.stringify():JavaScriptのオブジェクト → JSON(文字列)

 

json.html

<html>
<body>
<script>
var object = {};
//var object = new Object();
//object.key0 = "value0";
//object.key1 = "value1";
//object.key2 = "value2";
object["key0"] = "value0";
object["key1"] = "value1";
object["key2"] = "value2";
document.body.innerHTML += JSON.stringify(object) + "<br>";
document.body.innerHTML += JSON.stringify({key0:"value0", key1:"value1", key2:"value2"}) + "<br>";
for (var key in object) {
  document.body.innerHTML += key + ":" + object[key] + "<br>";
}
document.body.innerHTML += JSON.stringify({key0:0, key1:"abc", key2:[0, 1, "xyz"]}) + "<br>";
var json = '{"key0":0, "key1":"abc", "key2":[0, 1, "xyz"]}';
var object = JSON.parse(json);
document.body.innerHTML += object["key0"] + "<br>";
document.body.innerHTML += object["key1"] + "<br>";
document.body.innerHTML += object["key2"] + "<br>";
</script>
</body>
</html>
 

配列

 

array.html

<html>
<body>
<script>
var array = [];
array[0] = "a0";
array[1] = "a1";
array[2] = "a2";
//var array = new Array();
//array.push("a0");
//array.push("a1");
//array.push("a2");
//array.pop();
for (var index in array) {
  document.body.innerHTML += index + ":" + array[index] + "<br>";
}
</script>
</body>
</html>
 

連想配列

連想配列(associative array )を、波括弧(curly bracket){} ではなく、角括弧(square bracket)[] で初期化しても動作した。

 

associative_array .html

<html>
<body>
<script>
var array = [];
//array = {};
array["key1"] = "value1";
array["key2"] = "value2";
array["key3"] = "value3";
for (var key in array) {
  document.body.innerHTML += key + ":" + array[key] + "<br>";
}
</script>
</body>
</html>
 

 

function_with_index.html (インデクス付関数)

<html>
<body>
<script>
var dispatch = {};
dispatch["abcde"] = function () {document.write("<p>abcde</p>");};
dispatch["fghij"] = function () {document.write("<p>fghij</p>");};
dispatch["klmno"] = function () {document.write("<p>klmno</p>");};
</script>
<script>
dispatch["abcde"]();
dispatch["fghij"]();
dispatch["klmno"]();
</script>
</body>
</html>
 

オブジェクト指向プログラミング

以下のプログラムの中で、関数Robotからnewで生成されたrobotはオブジェクトの参照を表わします。

robot1.html

<html>
<body>
<script>
function Robot(x, y) {
  this.x = x; // -> public
  this.y = y; // -> public
  this.move = function (dx, dy) {
    this.x += dx;
    this.y += dy;
  }
  this.show = function () {
    document.write("x = " + this.x + "<br>");
    document.write("y = " + this.y + "<br>");
  }
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
</script>
<script>
function f(robot) {
  robot.x = 2;
  robot.y = 2;
}
f(robot);
robot.show();
</script>
</body>
</html>
 

 

robot2.html

<html>
<body>
<script>
function Robot(x, y) {
  var x = x; // -> private
  var y = y; // -> private
  this.move = function (dx, dy) {
    x += dx;
    y += dy;
  }
  this.show = function () {
    document.write("x = " + x + "<br>");
    document.write("y = " + y + "<br>");
  }
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>"); // -> x = undefined
document.write("y = " + robot.y + "<br>"); // -> y = undefined
</script>
</body>
</html>
 

 

robot3.html

<html>
<body>
<script>
function Robot(x, y) {
  this.x = x; // -> public
  this.y = y; // -> public
}
Robot.prototype.move = function (dx, dy) {
  this.x += dx;
  this.y += dy;
};
Robot.prototype.show = function () {
  document.write("x = " + this.x + "<br>");
  document.write("y = " + this.y + "<br>");
};
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
robot.print = function () {
  document.write("x = " + this.x + "<br>");
  document.write("y = " + this.y + "<br>");
};
robot.print();
</script>
</body>
</html>
 

フォームデータの送信

input要素のname属性とvalue属性の値が下記の形式で送信されます。

http://xxxxx.xxxxx/?name1=value1&name2=value2&name3=value3

 

get.html

<html>
<body>
<form action="http://xxxxx.xxxxx" method="get">
  <input name="name1" value="value1">
  <input name="name2" value="value2">
  <input name="name3" value="value3">
  <button>送信</button>
</form>
</body>
</html>
 

 

submit.html

<html>
<body>
<form action="http://www.google.com/search" target="_blank">
  <input type="hidden" name="hl" value="ja">
  <input type="text" name="hq" placeholder="inurlを入力" size="50">
  <input type="text" name="q" placeholder="keywordを入力" size="50">
  <input type="submit" value="search">
</form>
</body>
</html>
 

 

submit.html

<html>
<head>
<script>
function request() {
  document.requestform.name1.value = document.getElementById("id1").value;
  document.requestform.name2.value = document.getElementById("id2").value;
  document.requestform.submit();
}
</script>
</head>
<body>
<form>
<input type="text" id="id1" value="value1" size="50" style="font-size:15pt">
<input type="text" id="id2" value="value2" size="50" style="font-size:15pt">
</form>
<form name="requestform" action="http://www.xxxxx.jp/request" target="_blank">
<input type="hidden" name="name1" value="">
<input type="hidden" name="name2" value="">
<input type="button" value="request" onclick="request()" style="width:100px; height:35px; font-size:15pt">
</form>
</body>
</html>
 

 

XMLHttpRequestの作成

post.html(ページ遷移する)

<html>
<body>

<form>
  <input type="button" value="実行" onclick="$execute('#input1', '#input2', '#output');">
  <input type="text" id="input1">
  <input type="text" id="input2">
  <output id="output"></output>
</form>

<script>
function $execute(input1, input2, output) {
  var url = "/websys/servlet";
  var request = {};
  request["class"] = "Arithmetic";
  request["method"] = "add";
  request["input1"] = document.querySelector(input1).value;
  request["input2"] = document.querySelector(input2).value;
  var callback = function (response) {document.querySelector(output).innerHTML = response["output"];};
  $post(url, request, callback);
}
</script>

<script>
function $post(url, request, callback) {
/*
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      callback(JSON.parse(this.responseText));
    }
  };
*/
  var form = document.createElement("form");
  var input = document.createElement("input");
  form.style.display = "none";
  form.method = "post";
  form.action = url;
  for (var key in request) {
    input.name  = key;
    input.value = request[key].toString();
    form.appendChild(input.cloneNode());
  }
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}
</script>

</body>
</html>
 

 

event1.html

<html>
<head>
</head>
<body>

<form name="io">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="button" name="button" value="実行" onclick="execute(0)">
<output name="output"></output>
</form>

<script>
function execute(x) {
  document.io.output.innerHTML = Number(x) + Number(document.io.input1.value) + Number(document.io.input2.value);
}
</script>

</body>
</html>
 

 

event2.html

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>

<form>
<input type="text" id="input1">
<input type="text" id="input2">
<input type="button" id="button" value="実行">
<output id="output"></output>
</form>

<script>
$("#button").on("click", function () {execute(0);});
//document.getElementById("button").addEventListener("click", function () {execute(0);}, false);
</script>

<script>
function execute(x) {
  document.getElementById("output").innerHTML = Number(x) + Number(document.getElementById("input1").value) + Number(document.getElementById("input2").value);
}
</script>

</body>
</html>
 

 

keyevent.html

<html>
<body>

<input type="text" id="input1">
<input type="text" id="input2">
<output id="output"></output>

<script>
document.getElementById("input1").onkeydown = function (event) {
  document.getElementById("output").innerHTML = String.fromCharCode(event.keyCode);
}
</script>

<script>
document.getElementById("input2").onkeyup = function () {
  document.getElementById("output").innerHTML = document.getElementById("input2").value;
}
</script>

</body>
</html>
 

 


 

array.html

<html>
<body>

<script>
var array = [];
array = ["a0", "a1", "a2", "a3", "a4"];
array = array.concat(["a5", "a6", "a7", "a8", "a9"]);
document.body.innerHTML += array + "<br>";
array.push("a10", "a11", "a12");
document.body.innerHTML += array + "<br>";
array.splice(5, 3, "a15", "a16", "a17");
document.body.innerHTML += array + "<br>";
array.splice(10, 3);
document.body.innerHTML += array + "<br>";
array = array.slice(5, 8);
document.body.innerHTML += array + "<br>";
</script>

<script>
array = ["a0", "a1", "a2", "a3", "a4"];
var string = array.join(",");
document.body.innerHTML += string + "<br>";
array = string.split(",");
document.body.innerHTML += array + "<br>";
string = "abcdefghij";
document.body.innerHTML += string.slice(2) + "<br>";
document.body.innerHTML += string.slice(2, 5) + "<br>";
document.body.innerHTML += string.substr(2, 3) + "<br>";
document.body.innerHTML += string.substring(2, 5) + "<br>";
</script>

</body>
</html>
 

ある外部ファイル(jsファイル)のグローバル変数を、別の外部ファイルから参照できる。外部ファイルの呼び出し順序に注意。
トップレベルの変数(グローバル変数)には、var が有っても無くても同じ意味。関数内の変数の場合は、var が無いとグローバル変数になる。

 

global.html

<html>
<body>
<script src="./a.js"></script>
<script src="./b.js"></script>
</body>
</html>
 

 

a.js

var $1 = 1;
var $2 = 2;
var $3 = 3;
 

 

b.js

document.body.innerHTML += $1 + "<br>";
document.body.innerHTML += $2 + "<br>";
document.body.innerHTML += $3 + "<br>";
 

 

indexOf.html

<html>
<body>
<script>
var array = ["abcde", "fghij", "klmno"];
document.write(array.indexOf("abcde") + "<br>"); // -> 0
document.write(array.indexOf("fghij") + "<br>"); // -> 1
document.write(array.indexOf("klmno") + "<br>"); // -> 2
</script>
</body>
</html>
 

 

redirect.html

<script>
$("#login").on("click", function () {
  var url = "/webapp/loginservlet";
  var request = {};
  request["user"] = $("#user").val();
  request["password"] = $("#password").val();
  $.post(url, request, redirect);
});
</script>

<script>
function redirect(response) {
  if (response["status"] === "success") {
    location.href = response["url"];
    //location.assign(response["url"]);
    //location.replace(response["url"]);
  }
  else {
    $("#message").text(response["error"]);
  }
}
</script>
 

loadイベントの使い方

 

window.onload.html

<html>
<body>
<script>
window.addEventListener("load", function () {
  document.getElementById("message").innerHTML += "Hello1!";
});
window.addEventListener("load", function () {
  document.getElementById("message").innerHTML += "Hello2!";
});
window.addEventListener("load", function () {
  document.getElementById("message").innerHTML += "Hello3!";
});
</script>
<out id="message"></out>
</body>
</html>
 

テーブル

 

table.html

<html>
<head>
<style>
table {
  //width:0;
  //table-layout:fixed;
  border:2px solid #555eee;
  border-collapse:collapse;
}
tr {
  height:25px;
}
th input[type="text"] {
  font-weight:bold;
  text-align:center;
}
tr th:nth-child(1), tr td:nth-child(1) {
  width:20px;
  text-align:center;
}
tr th:nth-child(2), tr td:nth-child(2) {
  //display:none;
}
input[type="text"] {
  width:100%;
  height:100%;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  //font-family:"MS PGothic";
  //font-size:15px;
  //color:#555555;
}
input {
  margin:0;
  padding:0;
}
</style>
</head>
<body>
<div id="id_div"></div>
<output id="id_output"></output>
<script>
$makeTable("id_div", 10, 5);
function $makeTable(id_div, rowsLength, columnsLength) {
  var table = document.createElement("table");
  table.border = 1;
  var div = document.getElementById(id_div);
  while (div.children[0]) div.removeChild(div.children[0]);
  div.appendChild(table);
  var thead = document.createElement("thead");
  table.appendChild(thead);
  var thead_tr = document.createElement("tr");
  thead.appendChild(thead_tr);
  var th0 = document.createElement("th");
  th0.width = 100;
  thead_tr.appendChild(th0);
  var th_checkbox = document.createElement("input");
  th_checkbox.type = "checkbox";
  //th_checkbox.onclick = function () {$checkAll(this);};
  th0.appendChild(th_checkbox);
  var th = [];
  for (var j = 0; j < columnsLength; j++) {
    th[j] = document.createElement("th");
    th[j].innerHTML = "item" + j;
    thead_tr.appendChild(th[j]);
  }
  var tbody = document.createElement("tbody");
  table.appendChild(tbody);
  var tbody_tr = [];
  var td = [];
  var input = [];
  for (var i = 0; i < rowsLength; i++) {
    tbody_tr[i] = document.createElement("tr");
    tbody.appendChild(tbody_tr[i]);
    var td0 = document.createElement("td");
    tbody_tr[i].appendChild(td0);
    var td_checkbox = document.createElement("input");
    td_checkbox.type = "checkbox";
    //td_checkbox.onchange = function () {$makeWritable(this);};
    td0.appendChild(td_checkbox);
    td[i] = [];
    input[i] = [];
    for (var j = 0; j < columnsLength; j++) {
      td[i][j] = document.createElement("td");
      tbody_tr[i].appendChild(td[i][j]);
      input[i][j] = document.createElement("input");
      input[i][j].type = "text";
      input[i][j].readOnly = false;
      input[i][j].value = i + "," + j;
      td[i][j].appendChild(input[i][j]);
    }
  }
  for (var i = 0; i < tbody.querySelectorAll("tr").length; i++) {
    for (var j = 0; j < thead.querySelectorAll("th").length; j++) {
      document.getElementById("id_output").innerHTML += tbody.rows[i].cells[j].children[0].value + "<br>";
    }
  }
}
</script>
</body>
</html>
 

 

table.html

<html>
<head>
<style>
table {
  //width:0;
  //table-layout:fixed;
  border-collapse:collapse;
  //border:2px solid #555eee;
}
tr {
  height:25px;
}
th input[type="text"] {
  font-weight:bold;
  text-align:center;
}
tr th:nth-child(1), tr td:nth-child(1) {
  width:20px;
  text-align:center;
}
tr th:nth-child(2), tr td:nth-child(2) {
  //display:none;
}
input[type="text"] {
  width:100%;
  height:100%;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  //font-family:"MS PGothic";
  //font-size:15px;
  //color:#555555;
}
input {
  margin:0;
  padding:0;
}
</style>
</head>
<body>
<div id="id_div"></div>
<script>
$makeTable("id_div", 10, 5);
function $makeTable(id_div, rowsLength, columnsLength) {
  var table = "<table border='2' bordercolor='#555eee' bgcolor='#ffffff' cellpadding='1'>";
  table += "<thead>";
  table += "<tr>";
  table += "<th><input type='checkbox'></th>";
  for (var j = 0; j < 5; j++) {
    table += "<th>item" + j + "</th>";
  }
  table += "</tr>";
  table += "</thead>";
  table += "<tbody>";
  for (var i = 0; i < rowsLength; i++) {
    table += "<tr>";
    table += "<td><input type='checkbox'></td>";
    for (var j = 0; j < columnsLength; j++) {
      table += "<td><input type='text' value=\"" + i + "," + j + "\" readonly></td>";
    }
    table += "</tr>";
  }
  table += "</tbody>";
  table += "</table>";
  document.getElementById(id_div).innerHTML = "";
  document.getElementById(id_div).insertAdjacentHTML("afterbegin", table);
};
</script>
</body>
</html>
 

テーブルにおける行・列の追加・削除

 

table.html

<html>
<head>
<style>
table {
  width: 50%;
  border-collapse: collapse;
}
</style>
</head>
<body>

<form>
  <input type="button" value="追加" onclick="$append();">
  <input type="button" value="削除" onclick="$remove();">
</form>

<table id="table0" border="1">
  <thead><tr><th><input type="checkbox" class="checkbox" onclick="$checkAll(this);"></th><th>item1</th><th>item2</th><th>item3</th></tr></thead>
  <tbody></tbody>
</table>

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>
document.querySelector("#table0 thead .checkbox").checked = false;
</script>

<script>
function $append() {
  var tr = "<tr><td><input type='checkbox' class='checkbox' onchange='$makeEditable(this);'></td><td>data1</td><td>data2</td><td>data3</td></tr>";
  //$("#table0 tbody").append(tr);
  document.querySelector("#table0 tbody").insertAdjacentHTML("beforeend", tr);
}
</script>

<script>
function $remove() {
  //$("#table0 tbody :checked").parent().parent().remove();
  var tbody = document.querySelector("#table0 tbody");
/*
  var length = tbody.rows.length; 
  while (length--) {
    var checkbox = tbody.rows[length].cells[0].firstElementChild;
    if (checkbox.checked === true) {
      tbody.deleteRow(length);
    }
  }
*/
  var checkboxes = document.querySelectorAll("#table0 tbody .checkbox");
  var length = checkboxes.length; 
  while (length--) {
    if (checkboxes[length].checked === true) {
      //tbody.children[length].remove();
      tbody.removeChild(tbody.children[length]);
    }
  }
  document.querySelector("#table0 thead .checkbox").checked = false;
}
</script>

<script>
function $checkAll(checkbox) {
  var checkboxes = document.querySelectorAll("#table0 tbody .checkbox");
  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = checkbox.checked;
  }
}
</script>

<script>
function $makeEditable(checkbox) {
  var tr = checkbox.parentNode.parentNode;
  if (checkbox.checked === true) {
    tr.contentEditable = true;
  }
  else {
    tr.contentEditable = false;
  }
}
</script>

</body> 
</html>
 

ダイアログボックスのフェードイン・フェードアウト

 

dialog.html

<html>
<head>
<style>
body {
  animation: fadein 5s ease 0s 1 normal;
  -webkit-animation: fadein 5s ease 0s 1 normal;
}
@keyframes fadein {
  0% {opacity: 0;}
  100% {opacity: 1;}
}
@-webkit-keyframes fadein {
  0% {opacity: 0;}
  100% {opacity: 1;}
}
#dialog {
  width: 50%;
  height: 200px;
  background: #555eee;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<div id="dialog"></div>
</script>
</body>
</html>
 

 

dialog.html

<html>
<head>
<style>
#dialog {
  width: 50%;
  height: 200px;
  background: #555eee;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<input type="button" value="open" onclick="$open();">
<input type="button" value="close" onclick="$close();">
<div id="dialog" class="box" style="visibility:hidden;"></div>
<script>
function $open() {
  document.querySelector("#dialog").style.visibility = "visible";
}
function $close() {
  document.querySelector("#dialog").style.visibility = "hidden";
}
</script>
</body>
</html>
 

 

dialog.html

<html>
<head>
<style>
.box {
  opacity: 0;
  visibility: hidden;
  transition: opacity 2s, visibility 0s ease 1s;
}
.box.visible {
  opacity: 1;
  visibility: visible;
  transition-delay: 0s;
}
#dialog {
  width: 50%;
  height: 200px;
  background: #555eee;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<input type="button" value="open" onclick="$open();">
<input type="button" value="close" onclick="$close();">
<input type="button" value="toggle" onclick="$toggle();">
<div id="dialog" class="box"></div>
<script>
function $open() {
  document.querySelector("#dialog").classList.add("visible");
}
function $close() {
  document.querySelector("#dialog").classList.remove("visible");
}
function $toggle() {
  document.querySelector("#dialog").classList.toggle("visible");
}
</script>
</body>
</html>
 

入力チェック

string.match(/regexp/) → stringの中にregexpがあれば最初の文字列を返す。なければnullを返す
string.match(/regexp/g) → stringの中にregexpがあれば全ての文字列の配列を返す。なければnullを返す
[^0-9a-zA-Z] → 英数字以外の一文字を表わす。
if(string.match(/[^0-9a-zA-Z]/)) → stringの中に英数字以外の文字が一文字でもあればtrueになる。

 

regex.html

<html>
<body>
<form>
  <input type="button" value="OK" onclick="$check('#input', '#output')">
  <input type="text" id="input" placeholder="input">
  <output id="output"></output>
</form>
<script>
function $check(input, output) {
  var input = document.querySelector(input).value;
  var output = document.querySelector(output);
  try {
    if (/[^0-9]/.test(input) || input == "") throw "Input is not a number!"; //0~9以外の文字を含むかどうかをチェック
    output.innerHTML = "Input is a number!";
  }
  catch (e) {
    output.innerHTML = e;
  }
}
/*
function $check(input, output) {
  var input = document.querySelector(input).value;
  var output = document.querySelector(output);
  try {
    if (/^(0|[1-9]\d*)$/.test(input)) throw "Input is a unsigned number!"; //符号無し整数であるかどうかをチェック
    output.innerHTML = "Input is not a unsigned number!";
  }
  catch (e) {
    output.innerHTML = e;
  }
}
*/
</script>
<script>
document.body.innerHTML += "abc".match(/ab/) + "<br>"; //"ab"を含む文字列
document.body.innerHTML += "abc".match(/[abc]/g) + "<br>"; //"a"、"b"、"c"のいずれかにマッチするかどうかをチェック
document.body.innerHTML += "abc".match(/[^0-9]/g) + "<br>";
document.body.innerHTML += "abc".match(/[^0-9]+/g) + "<br>";
</script>
</body>
</html>
 

 

input_validation1.html

<html>
<body>
<p>正の数を入力してください。平方根が出力されます。</p>
<form>
  <input type="button" value="sqrt" onclick="sqrt('#input', '#output')">
  <input type="text" id="input" placeholder="input">
  <output id="output"></output>
</form>
<script>
function sqrt(input, output) {
  var input = document.querySelector(input).value;
  var output = document.querySelector(output);
  try {
    if (input == "") throw "Input is empty!";
    if (isNaN(input)) throw "Input is not a number!";
    if (Number(input) < 0) throw "Input is a negative number!";
    output.innerHTML = Math.sqrt(Number(input));
  }
  catch (e) {
    output.innerHTML = e;
  }
}
</script>
</body>
</html>
 

 

input_validation2.html

<html>
<body>
<p>正の数を入力してください。平方根が出力されます。</p>
<form>
  <input type="button" value="sqrt" onclick="sqrt('#input', '#output')">
  <input type="text" id="input" placeholder="input">
  <output id="output"></output>
</form>
<script>
function sqrt(input, output) {
  var input = document.querySelector(input).value;
  var output = document.querySelector(output);
  try {
    if (input == "") throw new Error("Input is empty!");
    if (isNaN(input)) throw new Error("Input is not a number!");
    if (Number(input) < 0) throw new Error("Input is a negative number!");
    output.innerHTML = Math.sqrt(Number(input));
  }
  catch (e) {
    output.innerHTML = e.message;
  }
}
</script>
</body>
</html>
 

配置

 

table_center.html(上下左右中央)

<!doctype html>
<html>
<head>
<style>
html, body {
  margin:0;
  //padding:0;
  height:100%;
}
.center {
  display:flex;
  height:100%;
  align-items:center;
  justify-content:center;
  -webkit-align-items:center;
  -webkit-justify-content:center;
}
</style>
</head>
<body>
<table class="center" border="1" bordercolor="blue" style="border-collapse:collapse;">
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
</table>
</body>
</html>
 

 

table_center.html(上下左右中央)

<!doctype html>
<html>
<head>
<style>
html, body {
  margin:0;
  //padding:0;
  height:100%;
}
.table {
  display:table;
  width:100%;
  height:100%;
}
.vertical_center {
  display:table-cell;
  vertical-align:middle;
}
.horizontal_center {
  display:table;
  margin:auto;
}
</style>
</head>
<body>
<div class="table">
  <div class="vertical_center">
    <div class="horizontal_center">
      <table border="1" bordercolor="blue" style="border-collapse:collapse;">
        <tr>
          <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
        </tr>
        <tr>
          <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
        </tr>
        <tr>
          <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
        </tr>
        <tr>
          <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
        </tr>
        <tr>
          <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
        </tr>
      </table>
    </div>
  </div>
</div>
</body>
</html>
 

 

box_center.html(上下左右中央)

<!doctype html>
<html>
<head>
<style>
html, body {
  margin:0;
  //padding:0;
  height:100%;
}
.table {
  display:table;
  width:100%;
  height:100%;
}
.vertical_center {
  display:table-cell;
  vertical-align:middle;
}
.horizontal_center {
  display:table;
  margin:auto;
}
.box {
  display:table-cell;
  text-align:center;
  vertical-align:middle;
  width:300px;
  height:200px;
  background-color:blue;
}
</style>
</head>
<body>
<div class="table">
  <div class="vertical_center">
    <div class="horizontal_center">
      <div class="box">
        xxxxxxxxxx<br>
        xxxxxxxxxx<br>
        xxxxxxxxxx<br>
      </div>
    </div>
  </div>
</div>
</body>
</html>
 

 

table_center.html(左右中央)

<!doctype html>
<html>
<head>
<style>
.center {
  display:table;
  margin:auto;
}
.center {
  //margin-left:auto;
  //margin-right:auto;
}
.center {
  //left:0;
  //right:0;
  //margin:auto;
}
</style>
</head>
<body>
<table class="center" border="1" bordercolor="blue" style="border-collapse:collapse;">
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
  <tr>
    <td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
  </tr>
</table>
</body>
</html>
 

 

position.html(上下左右中央)

<html>
<head>
<style>
html, body {
  //width:100%;
  //height:100%;
}
.outter {
  //position:relative;
  height:100%;
  //width:200px;
  //height:200px;
  background:silver;
}
.inner {
  width:100px;
  height:100px;
  background:blue;
}
.center {
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  margin:auto;
}
</style>
</head>
<body>
<div class="outter">
  <div class="inner center">
    Hello!
  </div>
</div>
</body>
</html>
 

 

position.html(左右中央)

<html>
<head>
<style>
html, body {
  //width:100%;
  //height:100%;
}
.outter {
  //position:relative;
  height:100%;
  //width:200px;
  //height:200px;
  background:silver;
}
.inner {
  width:100px;
  height:100px;
  background:blue;
}
.center {
  position:relative;
  top:100px;
  margin:auto;
}
</style>
</head>
<body>
<div class="outter">
  <div class="inner center">
    Hello!
  </div>
</div>
</body>
</html>
 

 

absolute.html

<html>
<head>
<style>
.outter {
  position:relative;
  width:200px;
  height:200px;
  background:silver;
}
.inner {
  width:100px;
  height:100px;
  background:blue;
}
.center {
  position:absolute;
  top:50px;
  right:0;
  left:0;
  margin:auto;
}
</style>
</head>
<body>
<div class="outter">
  <p>xxxxxxxxxx</p>
  <div class="inner center">
    Hello!
  </div>
</div>
</body>
</html>
 

 

relative.html

<html>
<head>
<style>
.outter {
  width:200px;
  height:200px;
  background:silver;
}
.inner {
  width:100px;
  height:100px;
  background:blue;
}
.center {
  position:relative;
  top:50px;
  right:0;
  left:0;
  margin:auto;
}
</style>
</head>
<body>
<div class="outter">
  <p>xxxxxxxxxx</p>
  <div class="inner center">
    Hello!
  </div>
</div>
</body>
</html>
 

 

float.html

<html>
<body>
<div style="position:relative;">
  <div style="float:left;">
    aaaaa
  </div>
  <div style="float:right;">
    bbbbb
  </div>
  <div style="clear:both;">
    ccccc
  </div>
  <div style="position:absolute; bottom:0; right:0;">
    ddddd
  </div>
</div>
</body>
</html>
 

表示・非表示

 

switch.html

<html>
<body>
<input type="radio" id="radio0" name="menu" checked="false" onclick="$switch()">menu0<br>
<input type="radio" id="radio1" name="menu" checked="false" onclick="$switch()">menu1<br>
<input type="radio" id="radio2" name="menu" checked="false" onclick="$switch()">menu2<br>
<div id="box0" style="display:none; width:500px; height:300px; background:#777777;">box0</div>
<div id="box1" style="display:none; width:500px; height:300px; background:#555eee;">box1</div>
<div id="box2" style="display:none; width:500px; height:300px; background:#eee555;">box2</div>
<script>
document.querySelector("#radio0").checked = true;
document.querySelector("#box0").style.display = "block";
function $switch() {
  var radios = document.getElementsByName("menu");
  for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
      for (var j = 0; j < radios.length; j++) {
        document.querySelector("#box" + j).style.display = "none";
      }
      document.querySelector("#box" + i).style.display = "block";
      break;
    }
  }
}
</script>
</body>
</html>
 

 

display.html

<html>
<body>
<input type="button" value="表示" onclick="document.querySelector('#box').style.display='block';">
<input type="button" value="非表示" onclick="document.querySelector('#box').style.display='none';">
<div id="box" style="display:none">
  <p>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
  </p>
</div>
<div>
  <p>
    yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
    yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
  </p>
</div>
</body>
</html>
 

 

visibility.html

<html>
<body>
<input type="button" value="表示" onclick="document.querySelector('#box').style.visibility='visible';">
<input type="button" value="非表示" onclick="document.querySelector('#box').style.visibility='hidden';">
<div id="box" style="visibility:hidden">
  <p>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
  </p>
</div>
<div>
  <p>
    yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
    yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
  </p>
</div>
</body>
</html>
 

iframe

 

main.html

<!doctype html>
<html>
<body>
<iframe id="id_iframe" src="sub1.html" width="300" height="200" frameborder="1"></iframe>
<input id="id_input" type="text" value="">
<input type="button" value="Print" onclick="$print();">
<script>
function $replaceSrc(src) {
  document.getElementById("id_iframe").contentWindow.location.replace(src);
}
</script>
<script>
function $print() {
  document.body.innerHTML += document.getElementById("id_iframe").contentWindow.document.getElementById("id_input").value;
}
</script>
</body>
</html>
 

 

sub1.html

<!doctype html>
<html>
<body>
<h1>sub1.html</h1>
<input id="id_input" type="text" value="">
<input type="button" value="OK" onclick="$hoge();">
<script>
function $hoge() {
  //window.parent.document.getElementById("id_input").value = "Hello!";
  //window.parent.$replaceSrc('sub2.html');
  window.top.document.getElementById("id_input").value = "Hello!";
  window.top.$replaceSrc('sub2.html');
}
</script>
</body>
</html>
 

 

sub2.html

<!doctype html>
<html>
<body>
<h1>sub2.html</h1>
<input id="id_input" type="text" value="">
</body>
</html>
 

2次元配列

 

array2d.html

<html>
<body>
<script>
var array2d = [];
for (var i = 0; i < 10; i++) {
  array2d[i] = [];
  for (var j = 0; j < 20; j++) {
    array2d[i][j] = "(" + i + "," + j + ")";
  }
  document.body.innerHTML += array2d[i].join(',') + "<br>";
}
</script>
</body>
</html>
 

var & let

let_var.html

<html>
<body>
<script>
function printx() {
  let x = 0;
  document.body.innerHTML += x + "<br>";
  {
    let x = 1;
    document.body.innerHTML += x + "<br>";
  }
  document.body.innerHTML += x + "<br>";
}
printx();
</script>
<script>
function printy() {
  var y = 0;
  document.body.innerHTML += y + "<br>";
  {
    var y = 1;
    document.body.innerHTML += y + "<br>";
  }
  document.body.innerHTML += y + "<br>";
}
printy();
</script>
</body> 
</html>
 

セレクタ

.aaa.bbb {} と .aaa .bbb {} は、意味が異なるので注意!
.aaa.bbb {} は、<div class="aaa bbb"></div>のような要素に対する設定!
#aaa.bbb {} は、<div id="aaa" class="bbb"></div>のような要素対する設定!
.aaa .bbb {} → aaa の子孫である bbb (直下でなくてもよい)
.aaa > .bbb {} → aaa の直下にある bbb
尚、.abc は、*.abc を表す。

 

selector.html

<html>
<head>
<link rel="stylesheet" type="text/css" href="sample.css">
</head>
<body>
<div id="id1">aaaaa</div>
<div class="class1">bbbbb<div class="class2">ccccc</div>ddddd</div>
</body>
</html>
 

 

selector.html

div#id1 {color: red;}
div.class1 {color: blue;}
div.class1 > div.class2 {color: green;}
 

 

selector.html

<html>
<body>
<div>
  <p>aaaaa</p>
  <p>bbbbb</p>
  <p>ccccc</p>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("p").eq(0).css("color", "blue");
$("div").find("p").eq(2).css("color", "red");
Array.from(document.querySelectorAll("p"), element => document.body.innerHTML += element.textContent);
</script>
</body>
</html>
 

 

selector.html

$(".abc").eq(0); -> jQuery Object
document.querySelectorAll(".abc")[0]; -> NodeList

$(element).find(".abc").eq(0); -> jQuery Object
element.querySelectorAll(".abc")[0]; -> NodeList
 

 

selector.html

<form>
<input type="button" id="ibutton" value="実行">
<input type="button" class="cbutton" value="実行">
</form>

<script>
$("#ibutton").on("click", function () {.....});
$(".cbutton").on("click", function () {.....});
</script>
 

Default Parameter

注)ECMAScript 5.1 で undefined は書き換え不可になった。

 

default_parameters.html

<html>
<body>
<script>
function f(x) {
  if (x === undefined) {
    x = "Hello!";
  }
  document.body.innerHTML += x + "<br>";
}
/* IE NG
function f(x = "Hello!") {
  document.body.innerHTML += x + "<br>";
}
*/
</script>
<script>
f();
f(null);
f(undefined);
f("Goodbye!");
</script>
</body>
</html>
 

 

immediate_function.html

(function () {
  .....
} ());
 

<br>: line break


参考サイト