简体   繁体   English

HTML,JavaScript:将新元素添加到当前的空元素

[英]HTML, Javascript: Append a new element to the current empty element

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. 如果可能的话,只使用纯JavaScript。

<div id="container">


</div>

if the container has only whitespaces then: 如果容器只有空格,则:

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

VS VS

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

if the container has content (no need to append EMPTY): 如果容器包含内容(无需附加EMPTY):

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

You could check to see if the trim med innerHTML is the empty string: 您可以检查trim med innerHTML是否为空字符串:

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

how to check for emptiness 如何检查空虚

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

how to append 如何追加

if(isEmpty) document.getElementById("container").innerText = "EMPTY";

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM