Search code examples
htmltypescriptinnerhtml

`innerHTML` not working with `input` tag but `value `does


I am learning the MEAN stack. I'm performing CRUD operations. I'm stuck with update. Not with the operation exactly. Actually before updating a previously posted article I want to load contents in text fields for final changes. Those text fields are title and content. Where title is a simple text field and content is quill text editor value. Here is my articles.component.html

Title:<br>
<input type="text" id="title-container" name="title" >
<br>
Content:<br>
<input type="text" id="content-container" name="content">
<br><br>
<input type="submit" value="Submit">

and here's my article.component.ts This method is called from somewhere else when I click edit button.

onPress2(id) {
    this._articleService.fetchArticle(id)
    .subscribe (
      data => {
        document.querySelector('#title-container').innerHTML=data.title;
        document.querySelector('#content-container').innerHTML=data.content;
      }
    );
  }

Everything works perfectly if I replace innerHTML with value. But I cannot do so because my content field has value something like <h1>How to make Cheese cake</h1><br>... because I am using quill text editor. Please tell me what wrong with this code.


Solution

  • I did some more research on html elements. Here are my observations and solution. You cannot use innerHTML on input tag because it is a self closing tag and innerHTML as the name suggests works with tags which have both opening and closing tags For eg. div, 'span', etc. So, innerHTML and value are two different things.

    Solution

    Instead of an input tag, you can use div and add an attribute contentEditable="true" which will make it editable like input field:

    <div contentEditable="true" id="content-container" value="">
    </div>
    

    This will solve the problem. And in ts file. You are good to use:

    ...
    document.querySelector('#content-container').innerHTML=data.content;
    ...