Search code examples
javascripthtmlinnerhtml

How can I add an element created in Javascript to innerHTML


const totalBill = document.querySelector(".total-bill");
let errorDiv = document.querySelector(".error");

function isValid(e) {
  if (totalBill.value.trim().length == 0) {
    let para = document.createElement("div");
    para.innerText = "Please enter the total amount of bill";
    // para.classList.add("bill-para");
    para.setAttribute('class', 'bill-error')
    console.log(para);
    errorDiv.innerHTML = para;
  }

  e.preventDefault();
}

HTML:

<div class="container">
        <div class="error">
            
        </div>
        <div class="box-container">
            <h1 class="heading">TIP CALCULATOR</h1>
            <form action="">
                <div class="box">
                    <label>How much was your bill?</label><br>
                    <input type="number" placeholder="Total Bill" class="total-bill">
                </div>
            </form>
       </div>  

So I am trying to add a div in div.error section and I want to add div named div.bill-error but whenever I am trying to replace the innerHTML and run the code. It shows me '[Object HTMLDivElement]' instead of "Please enter the total amount of bill". But in the console I see that the div is created. But it is not inserted inside

Can anyone tell me where is the problem and solution. Thanks a lot.


Solution

  • Use errorDiv.appendChild(para);, or, if you want to delete existing content in errorDiv first, then errorDiv.textContent = ''; errorDiv.appendChild(para);.