我的 div 包含一个元素,但在使用 .children() 进行迭代时该元素未显示

My div includes an element, but the element doesn't show up when iterating using .children()

这是我在 Django 应用程序中使用的 html:

<div id="mahal_questions" class="showHide_div">
                        {{soldier.mahal_status.label_tag}}
                        {{soldier.mahal_status}}
    {{soldier.mahal_status.errors}}
                        {{soldier.mahal_program.label_tag}}
                        {{soldier.mahal_program}}
    {{soldier.mahal_program.errors}}
    <p>
                        {{soldier.mahal_id.label_tag}}
                        {{soldier.mahal_id}}
    {{soldier.mahal_id.errors}}</p>
</div>
                        {{soldier.currently_serving.label_tag}}
                        {{soldier.currently_serving}}
<div id="currently_serving_questions" class="showHide_div">
                        {{soldier.idf_id.label_tag}}
                        {{soldier.idf_id}}
    {{soldier.idf_id.errors}}
    <p></p> <!--prevents the error message from running into the next label-->
                        {{soldier.army_unit.label_tag}}
                        {{soldier.army_unit}}
    {{soldier.army_unit.errors}}
                        <p>{{soldier.tafkid.label_tag}}
                        {{soldier.tafkid}}
                            {{soldier.tafkid.errors}}</p>
</div>

我这里有两个 div,每个都包含 3 个字段。 mahal_questions 包括 mahal_status、mahal_program 和 mahal_id currently_serving_questions包括 idf_id、army_unit 和 tafkid 字段。

但出于某种原因,当我循环遍历 div 并在每个 div 中循环遍历我的元素时,我只看到每个 div 中的前两个元素。最后一个元素被忽略。 (我认为这个问题可能是在我添加一些 <p> 元素时开始的,但我不确定。)

这是我的 js(该方法旨在遍历页面上的每个 div,如果 div 隐藏,则循环遍历元素并在提交时擦除它们的值,以便隐藏字段' 值不会发送到数据库):

 $('#intake_form').submit(function() {
  var showhideDivList = document.getElementsByClassName("showHide_div"); //To avoid errors on a page with no show/hides
        if (showhideDivList.length > 0) {
            //get each show/hide div
            Array.from(showhideDivList).forEach(function (div) {
                console.log(div);
                //if this div is hidden
                if ($(div).is(":hidden")){
                    // //for each element that is going to be shown/hidden within the div
                    var elements = $(div).children();
                    console.log("elements.length:" + elements.length);
                    for (var i = 0; i < elements.length; i++) {
                        var element = elements.eq(i);
                        console.log(element);
                        console.log("value", element.val());
                        element.val("");
                        console.log("value", element.val());
                    }
                }
            });
        }
});

在评论中查看 Pointy 的回答。 问题是我有两个 "missing" 字段包含在 <p> 标签中,所以 .children() 函数正在获取 <p>s 而不是 <p> 中的元素秒。谢谢你,尖头!

所以为了解决这个问题,我只是将 <p></p> 放在 mahal_id 和 tafkid 字段之前,将它们的标签推到错误消息之后的行上,然后它们直接位于各自的 div 下,并将包含在 .children() 函数的结果中。