0
0

JavaScript DOM

Last updated at Posted at 2023-11-20

DOMって何?

JavaScriptから、HTMLを操作できる

DOMでHTML要素を書き換えよう

dom.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ブログ</title>
</head>
<body>
  <h1 id="dom">ブログ</h1>
  <form id="post-form">
    <label for="title">タイトル:</label><br>
    <input type="text" id="title" name="title"><br>
    <label for="content">本文:</label><br>
    <textarea id="content" name="content"></textarea><br>
    <input type="submit" value="Submit">
  </form>
  <div id="posts"></div>
  <script src="dom.js"></script>
</body>
</html>

dom.js

var dom = document.getElementById('dom');
dom.innerHTML = "シンプルブログ";

これは、
dom.htmlのh1(ブログ)をh1(シンプルブログ)に変更している

イベントハンドラを設定してみよう 〜なんか凄そう〜

dom/html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ブログ</title>
</head>
<body>
  <h1 id="dom">ブログ</h1>
  <form id="post-form">
    <label for="title">タイトル:</label><br>
    <input type="text" id="title" name="title"><br>
    <label for="content">本文:</label><br>
    <textarea id="content" name="content"></textarea><br>
    <input type="submit" value="Submit" id="submit">
  </form>
  <div id="posts"></div>
  <script src="dom.js"></script>
</body>
</html>

dom.js

document.getElementById('post-form').addEventListener('submit', function() {

  // タイトルと本文を取得
  const title = document.getElementById('title').value;
  const content = document.getElementById('content').value;

  // コンソールに出力
  console.log(title);
  console.log(content);
});

このコードは、
送信ボタンをクリックすると、
タイトルとコンテンツの文章をコンソールに出力する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0