user12051965
user12051965

Reputation: 147

Get content from contenteditable div

I display a popup for the user where it is required to write some text, and I want to check if he wrote something to display the message accordingly.

HTML

<div id="pop-div-id" class="cont-pop-div">
  <p id="content-id" contenteditable="true" class="cont-pop" placeholder="type explanation" spellcheck="false"></p>
</div>

Here is my JavaScript. I commented the use of textContent because I kept getting content has undefined value. The issue here is that this always alerts You have to write something and I am not sure what I am doing wrong that the value is not being updated even if I write something there.

let content =  document.getElementById("content-id");
// let contentValue = content.textContent;
// console.log(contentValue);

let innerText = content.innerText;

   if (innerText[innerText.length-1] === '\n') { 
      innerText = innerText.slice(0,-1);
      console.log(innerText);
   }            

button.addEventListener("click", function () {
  if (innerText.length === 0 || !!innerText.trim()) {
     alert("You have to write something ");
  } else {
     alert("Hello");
  }
});

I have seen this similar post - get the text content from a contenteditable div through javascript but apparently I am doing something wrong

Upvotes: 2

Views: 2483

Answers (1)

shreyasm-dev
shreyasm-dev

Reputation: 2834

Use the innerHTML attribute

console.log(document.querySelector('div').innerHTML)
<div contenteditable>
  Hello World!
  <img src='http://via.placeholder.com/150'>
</div>

MDN reference for innerHTML

If you want to only get the text and not any HTML inside it, use innerText

console.log(document.querySelector('div').innerText) // Will not include <img src='http://via.placeholder.com/150'>
<div contenteditable>
  Hello World!
  <img src='http://via.placeholder.com/150'>
</div>

MDN reference for innerText

Upvotes: 3

Related Questions