0

How can I check if an element has a content (except whitespaces) then append a new element if the element has no content? Just pure javascript if possible.

<div id="container">


</div>

if the container has only whitespaces then:

<div id="container">EMPTY</div>

VS

<div id="container">I am not empty</div>

if the container has content (no need to append EMPTY):

<div id="container">I am not empty</div>

3 Answers 3

1

how to check for emptiness

var isEmpty = !document.getElementById("container").innerText.trim();

how to append

if(isEmpty) document.getElementById("container").innerText = "EMPTY";
Sign up to request clarification or add additional context in comments.

Comments

1

You could check to see if the trimmed innerHTML is the empty string:

document.querySelectorAll('div').forEach(div => {
  if (div.innerHTML.trim() === '') div.textContent = 'Empty';
});
<div></div>
<div>


</div>

<div>I am not empty</div>

Comments

1

Like so:

var checkDivs = () => {
  document.querySelectorAll('#container').forEach((el)=>{
    el.innerText = (el.innerText) ? el.innerText:'EMPTY';
  })
}
checkDivs();
<div id="container">


</div>
if the container has only whitespaces then:
<div id="container">EMPTY</div>

VS

<div id="container">I am not empty</div>
if the container has content (no need to append EMPTY):
<div id="container">I am not empty</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.