Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')

hi Я пытаюсь следовать приведенному ниже руководству для моего набора форм, но я обнаружил проблему в части:

container.insertBefore (newForm, addButton)

и ошибка, которую я вижу, следующая:

calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')

Я уже все перепробовал, но не могу найти childNode

JS

let parteForm = document.querySelectorAll(".part-form")
let container = document.querySelector("#part-form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing


addButton.addEventListener('click', addForm)

function addForm(){
    //e.preventDefault()
    let newForm = parteForm[0].cloneNode(true)
    let formRegex = RegExp(`form-(\\d){1}-`,'g')
    formNum++
    newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)

    container.insertBefore(newForm, addButton)

    //parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode)
    //#part-form-container.insertbefore(div.part-form,)

    totalForms.setAttribute('value', `${formNum+1}`)
}

HTML


<form method="POST" id="part-form-container">
{% csrf_token %}

<div class="row">
<div class="col-12">
   <div class="card">
        <div class="card-body">
            <div class="row mb-3">
                   <div class="col-md-12">
                    <div class="mb-3">
                       <label for="verticalnav-email-input">Summary</label>                                                               
                     {{presupuestosparteform.resumen}}

                   </div>
                 </div>
               </div>


<h4 class="card-title">Parts list</h4>
<p class="card-title-desc">Add the parts that you need to include.</p>

<input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" />
<div class="table-responsive">
<table class="table table-bordered table-nowrap align-middle" id="childTable1">
                                                                                
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="part-form">
        <tr>
           <td>
                                                                                        
                   {{form.codigo}}

                    </td>
                     <td>
                                                                                        
                   {{form.descripcion}}

                  </td>

                 </tr>
               </div>
             {% endfor %}

           </tbody>
       </table>
</form>

Возможно, я не понимаю ваш код, но мне кажется, что некоторые закрывающие теги "div" отсутствуют. Я предлагаю реорганизовать ваш код и почистить его.

Теперь о том, что касается ошибки

(https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore):

Метод insertBefore() интерфейса Node вставляет узел до узла ссылки в качестве дочернего узла указанного родительского узла.

Вам просто нужно убедиться, что в коинтере есть элемент, который вы хотите вставить перед этим, так что я думаю, что просто закрытие открытых тегов div решит проблему. Я также заметил, что нет элемента с Id="id_form-TOTAL_FORMS", поэтому setAttribute не может работать.

let parteForm = document.querySelectorAll(".part-form")
let container = document.querySelector("#part-form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing


addButton.addEventListener('click', addForm)

function addForm(){
    //e.preventDefault()
    let newForm = parteForm[0].cloneNode(true)
    let formRegex = RegExp(`form-(\\d){1}-`,'g')
    formNum++
    newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)

    container.insertBefore(newForm, addButton)

    //parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode)
    //#part-form-container.insertbefore(div.part-form,)
}
<form method="POST" id="part-form-container">



                <label for="verticalnav-email-input">Summary</label>


          <h4 class="card-title">Parts list</h4>
          <p class="card-title-desc">Add the parts that you need to include.</p>

          <input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" />
          
<tbody>
  <div class="part-form">
          <tr>
             <td>Data-1</td>
             <td>Data-2</td>
          </tr>
  </div>
</tbody>
</table>
</form>

Вернуться на верх