Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
JS: if innerhtml is empty, change innerhtml to something. HOW?

i'm new to js so i have a simple html element that has contenteditable="true" which i'm using as an input box. i want the innerhtml to change to "CAN'T BE EMPTY" when the user has typed nothing in the input box ( " " ) and apparently it doesn't work, any tips on how i can do it? this is my code (which is not working):

HTML: <p contenteditable="true" id="myparagraph">Input</p>

JS:

 if(document.getElementById("myparagraph").innerHTML == ""){
 document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}

i've also tried using the LENGTH property, but didn't work either:

    var plength = document.getElementById("myparagraph").innerHTML;
        var plength2 = plength.length;
if(plength2 == 0){
     document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's not empty. It's got a value of Input according to your HTML.

If you want to change the value when the user edits, you need to attach an event listener:

document.getElementById('myparagraph').addEventListener('input', (e) => {
  if (e.target.textContent.trim() === '') {
    e.target.textContent = 'Cannot be empty';
  }
})
<p contenteditable="true" id="myparagraph">Input</p>

Note that I changed the logic from using innerHTML to using textContent because otherwise remaining empty HTML tags can prevent the warning from triggering. (Firefox, for example inserts a <br> when there is no content.)

about 4 years ago · Juan Pablo Isaza Report

0

It would be better to display the warning anywhere than the content of the element you're trying to check. Add an event listener to the paragraph element. In the handler get the textContent from the element, and then show/hide the warning depending on whether that text is empty.

const para = document.querySelector('#para');
const warning = document.querySelector('#warning');

para.addEventListener('input', handleInput, false);

function handleInput() {
  const text = this.textContent;
  warning.textContent = text ? '' : 'Cannot be empty';
}
#para { border: 1px solid #565656; padding: 0.5em; }
#warning { color: red; }
<p contenteditable="true" id="para">Input</p>
<p id="warning"></p>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!