确定/查找HTML DIV元素是否为空或未使用JavaScript

Ala*_*lls 5 html javascript dom

还有一篇文章可能已经回答了我的问题.为了找到这个帖子,我需要搜索child nodes或者children.但问题是,我当时不知道子节点或HTML子节点是什么.

这不是一个jQuery问题.

我的问题是:如何确定HTML元素是空的还是不使用?例如:

<div id="UserRegistration"></div>
Run Code Online (Sandbox Code Playgroud)

以上<div>元素没有内容.与此相反:

<div id="UserRegistration">
    <label>Password:</label>
    <input type="password" id="password" placeholder="Your New Password" required maxlength="32"/>
    <label>Verify Password:</label>
    <input type="password" name="ReEnterPassword" id="reenterpassword" required maxlength="32"/><br/>  
</div>
Run Code Online (Sandbox Code Playgroud)

我故意将元素留空,然后在用户单击菜单选项卡时将HTML注入其中.但是如果用户多次单击菜单项,我不想多次注入相同的HTML.为了避免这种情况,我希望代码确定元素是否已经注入了内容.我想使用Web API接口和JavaScript.使用添加内容.innerHTML

document.getElementById('UserRegistration').innerHTML=VariableWithRetreivedContent;
Run Code Online (Sandbox Code Playgroud)

当用户单击Register菜单选项卡时,将运行一个函数.我已经尝试使用它来确定是否已添加内容,但它不起作用:

function goToRegistration(ElmtToGoTo, FileToGet) {
    //Use getElementById to get info from the ElmtToGoTo DIV
    // and put info into the el variable
    var el = document.getElementById(ElmtToGoTo);
    alert(el.value);
    // If element is already filled quit
    if (el.value === undefined || el.value === "")
      {
         /To Do:  Quit Here
      };

        //To Do: Get content and put it into DIV element
      };
Run Code Online (Sandbox Code Playgroud)

我得到的是undefinedDIV是否有任何内容.如何测试<div>元素是否已注入内容?

Fel*_*ing 8

元素通常没有value属性,只有表单控件元素具有这样的属性(例如input元素).所以,.value永远undefineddiv元素.

您可以检查元素有多少个子节点.如果没有,则元素为空:

if (el.childNodes.length === 0)
Run Code Online (Sandbox Code Playgroud)

如果您只将Element节点视为"内容",则可以使用.children:

if (el.children.length === 0)
Run Code Online (Sandbox Code Playgroud)

.children是元素节点的列表.如果您的元素仅包含文本,并且您不将其视为内容,.children则为空.

  • 非常好.或者,我喜欢这样做:`if(element.firstChild){/*element is non-empty*/}`或`if(!element.firstChild){/*element is empty*/}`. (3认同)