代码之家  ›  专栏  ›  技术社区  ›  Alan Wells

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

  •  6
  • Alan Wells  · 技术社区  · 12 年前

    还有一个帖子可能回答了我的问题。为了找到那个帖子,我需要搜索 child nodes children 但问题是,我当时不知道什么是子节点或HTML子节点。

    这不是jQuery问题。

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

    <div id="UserRegistration"></div>
    

    以上内容 <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>
    

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

    document.getElementById('UserRegistration').innerHTML=VariableWithRetreivedContent;
    

    当用户单击 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
          };
    

    我得到的是 undefined 无论DIV中是否有任何内容。我如何测试 <div> 元素已经注入了内容?

    2 回复  |  直到 8 年前
        1
  •  9
  •   Felix Kling    12 年前

    元素通常没有 value 属性,只有表单控件元素具有这样的属性(例如。 input elements ). 所以 .value 总是 undefined 对于div元素。

    你可以看看有多少 child nodes 元素具有。如果没有,则元素为空:

    if (el.childNodes.length === 0)
    

    如果你只考虑 元素节点 作为“内容”,您可以使用 .children 而是:

    if (el.children.length === 0)
    

    儿童 是元素节点的列表。如果您的元素只包含文本,而不将其视为内容, 儿童 将为空。

        2
  •  2
  •   Akhlesh    12 年前
    function goToRegistration(ElmtToGoTo, FileToGet) {
    //Use getElementById to get info from the ElmtToGoTo DIV
    // and put info into the el variable
     if(ElmtToGoTo){
     var el = document.getElementById(ElmtToGoTo);
    }else
    {
        alert("invalid element");
        return false;
    }
    //alert(el.innerHTML);
    // If element is already filled quit
    if (el.innerHTML === "") {
        el.innerHTML='<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/>';
    };
    
    // To Do: Get content and put it into DIV element
    }
    
    document.getElementById('btn').onclick=function(){
      goToRegistration('UserRegistration');
    };
    

    http://jsfiddle.net/xZHe9/3/