how to appendchild with addeventlistener

I want that by pressing a button, an element has been added to my page(DOM). That's my code:

const input = document.getElementById('test');
const button = document.getElementById('B');
const form = document.querySelector('form')
const message = document.createElement('h1');

function creat () {
 
  document.body.appendChild(message);
  console.log(message);
}

form.addEventListener('submit', creat)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./style.css">
  <title>Document</title>
</head>
<body>
  <form>
    <input id="test" type="text">
    <button id="B">submit</button>
  </form>

  <script src="./app.js"></script>
</body>
</html>

I don't understand why it doesn't work

Upvotes: 0

Views: 237

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You need to prevent form submission from redirecting with event.preventDefault(). And create a new h1 element inside the creat function.

And as a bonus, you may need to clear the input after appending the child and stay focused.

const input = document.getElementById('test');
const button = document.getElementById('B');
const form = document.querySelector('form')


function creat (e) {
  e.preventDefault();

  const message = document.createElement('h1');
  message.innerText = input.value;

  document.body.appendChild(message);
  
  input.value = ''
  input.focus()
}

form.addEventListener('submit', creat)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./style.css">
  <title>Document</title>
</head>
<body>
  <form>
    <input id="test" type="text">
    <button id="B">submit</button>
  </form>

  <script src="./app.js"></script>
</body>
</html>

Upvotes: 1

Related Questions