Search code examples
javascripthtmlparagraph

(p) element doesn't display when it should


Hi I'm trying to make a website editor with drag and drop feature I added an input field when you press a button and the text you type in becomes the inner text for a "p" element but the "p" element doesn't display Here's the code HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>HTML</title>
  
  <!-- HTML -->
  

  <!-- Custom Styles -->
  <link rel="stylesheet" href="style.css">
</head>

<body>
   <nav>
   <button class="button" id="h1">Header</button>
   <button class="button" id="h2">Header2</button>
   <button class="button" id="p">Text</button>
   <button class="button" id="img">Image</button>
   </nav>
   <input type="text" placeholder="type your text here" id="text-field">
<!-- Linking scripts -->
   <script type="module" src="main.js"></script>
   <script type="module" src="mouse.js"></script>
   <script type="module" src="header_button.js"></script>
   <script type="module" src="header2_button.js"></script>
   <script type="module" src="image_button.js"></script>
   <script src="text_button.js"></script>

JavaScript:

let text_button = document.getElementById('p')
let text_data_holder = document.getElementById('text-field')
let paragraph = document.createElement('p')
let text_data = ''
//Creating text
text_button.addEventListener('click', function() {
  text_data_holder.style.display = 'block'
})
text_data_holder.addEventListener('change', function(e) {
   e.preventDefault()
   text_data += e.target.value
    if(text_data == e.target.value){
     paragraph.innerText = text_data
     console.log(text_data)
    }
})

Solution

  • as mentioned, you have to add p somewhere to the DOM. e.g. with .after()

    let paragraph = document.createElement('p')
    text_data_holder.after(paragraph)
    let text_data = ''