HTML•関数
HTML インライン対話ロジック:script ノードと DOM イベント埋め込み
HTML 文書はインラインの <script> 実行ノードを通じて高度な対話性とリアルタイム計算を実現します。DOM 要素へ `addEventListener` でイベントを結び付け、入力値の取得と状態指標の計算、対象 DOM ノードの更新を行うことで、ビルドツール不要で軽量な完結型 Web ツールを構築できます。
構文
<script>
document.getElementById("calc-btn").addEventListener("click", () => {
// Execute custom calculation logic and mutate DOM nodes
});
</script>
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| <script> | Script Node | 文書ツリー内に直接実行可能なクライアントサイド JavaScript ロジックを埋め込みます。 |
| addEventListener() | Event API | ユーザー操作時に呼び出されるイベントハンドラコールバックを登録します。 |
| document.getElementById() | DOM Selector | 入力値の読み取りや内容更新のために要素参照を取得します。 |
| textContent / innerHTML | Node Property | 計算されたアプリ状態を反映するため対象要素のテキストや HTML を更新します。 |
そのまま実行できるコード例
Compilra で実行可能HTML をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cloud Compute Cost Estimator</title>
<style>
body { font-family: system-ui, -apple-system, sans-serif; background: #0b0f19; color: #f8fafc; padding: 24px; }
.calc-card { max-width: 460px; background: #1e293b; border-radius: 12px; border: 1px solid #334155; padding: 24px; }
h2 { margin-top: 0; color: #38bdf8; font-size: 20px; }
.control-group { margin-bottom: 16px; }
label { display: block; font-size: 13px; font-weight: 600; color: #94a3b8; margin-bottom: 6px; }
input[type="range"] { width: 100%; accent-color: #38bdf8; }
.val-display { float: right; font-weight: 700; color: #38bdf8; }
.result-box {
margin-top: 20px; padding: 16px; border-radius: 8px; background: #0f172a; border: 1px solid #334155;
display: flex; justify-content: space-between; align-items: center;
}
.cost-num { font-size: 24px; font-weight: 800; color: #34d399; font-family: monospace; }
</style>
</head>
<body>
<div class="calc-card">
<h2>Cluster Cost Forecaster</h2>
<div class="control-group">
<label>Cluster Nodes: <span id="nodes-val" class="val-display">8</span></label>
<input type="range" id="nodes-slider" min="1" max="64" value="8" />
</div>
<div class="control-group">
<label>Memory per Node (GB): <span id="ram-val" class="val-display">32</span></label>
<input type="range" id="ram-slider" min="8" max="256" step="8" value="32" />
</div>
<div class="result-box">
<span>Estimated Monthly:</span>
<span id="total-cost" class="cost-num">$409.60</span>
</div>
</div>
<!-- Inline interactive custom logic script injection node -->
<script>
const nodesSlider = document.getElementById('nodes-slider');
const ramSlider = document.getElementById('ram-slider');
const nodesVal = document.getElementById('nodes-val');
const ramVal = document.getElementById('ram-val');
const totalCost = document.getElementById('total-cost');
function recalculate() {
const nodes = parseInt(nodesSlider.value, 10);
const ram = parseInt(ramSlider.value, 10);
// Update reactive UI label displays
nodesVal.textContent = nodes;
ramVal.textContent = ram;
// Custom computational logic: Base rate $15/node + $0.80/GB RAM per month
const monthlyEstimate = (nodes * 15.0) + (nodes * ram * 0.80);
totalCost.textContent = '$' + monthlyEstimate.toFixed(2);
}
// Attach event listeners for real-time recalculation
nodesSlider.addEventListener('input', recalculate);
ramSlider.addEventListener('input', recalculate);
</script>
</body>
</html>期待される出力:
[Rendered Interactive Cost Estimator: Real-Time Sliders with Dynamic Metric Updates and Computed Monthly Forecast Output]
動作のしくみ: ステップ解説
- 20〜35行目: セマンティックな HTML レンジ入力コントロールと値表示ラベルを構築します。
- 42〜47行目: document.getElementById() を通じて DOM ノード参照を取得します。
- 49〜60行目: 数値入力を解析してコスト計算式を適用するカスタム recalculate 関数を定義します。
- 62〜64行目: 60fps で即座に反応する DOM 更新のため input イベントリスナーを登録します。
重要ポイント
- インラインの <script> タグは親 DOM ノードが解析された後、ブラウザコンテキストで同期的に実行されます。
- input イベントはスライダーを動かした瞬間に発火するため、change イベントより即応性の高いフィードバックが得られます。
- 算術計算の前には必ず基数 10 を指定した parseInt() または parseFloat() で数値文字列を変換してください。
- 計算結果の描画に innerHTML ではなく textContent を使うことでクロスサイトスクリプティング(XSS)脆弱性を防げます。
よくある間違い: DOMContentLoaded や defer なしで <head> 内にインラインスクリプトを配置すること
HTML 本体の解析前に document.getElementById() を実行すると null が返り、TypeError が発生します。
❌ 誤り
<!-- Script in <head> without waiting for body elements to load -->
<head><script>document.getElementById("btn").addEventListener(...); // Null error!</script></head>✅ 正しい例
<!-- Place script at the bottom of <body> or use DOMContentLoaded -->
<body>
<button id="btn">Click</button>
<script>document.getElementById("btn").addEventListener(...);</script>
</body>関連するHTMLチュートリアルとコンパイラ
DOM 操作:querySelector、textContent、innerHTML
document.querySelector と textContent を使って HTML 要素を選択・操作しましょう。
DOM イベントリスナー:addEventListener・Click・Input イベント
click、input、keyup イベントに対して addEventListener を使いユーザー操作へ応答します。
HTML5 Canvas API:2D 描画とアニメーション
HTML5 の <canvas> 要素を使ってカスタム 2D グラフィックス、パス、図形、アニメーションを描画しましょう。
HTML オンラインコンパイラ
Compilra IDE で開く