You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

insertBefore方法失效报错“新子元素包含父元素”的原因与解决

Fixing "The new child element contains the parent" Error in Your Code

Hey there! Let's break down why your code is throwing that error and get it working the way you want.

Why the Error Happens

Your mistake comes from misusing the insertBefore() method. Here's the play-by-play:

  1. First, you run age.parentNode.appendChild(h45); — this adds your new <h4> element after the age input (since appendChild places elements at the end of the parent's child list).
  2. Then you try h45.insertBefore(h45, age); — this is where things go wrong! The insertBefore() method belongs to the parent node, not the new element you created. When you call it on h45, JavaScript thinks you're trying to insert h45 as a child of itself (before age), which is logically impossible — hence the "The new child element contains the parent" error.

How to Fix It

You don't need both appendChild() and insertBefore(). Just use the parent node's insertBefore() directly to place your <h4> above the age input. We'll also add a check to avoid duplicate error messages if the user triggers the blur event multiple times.

Here's the corrected code:

var lastName = document.getElementById("lastName");
var firstName = document.getElementById("firstName");
var age = document.getElementById("alter");

age.addEventListener("blur", showage, false);

function showage() {
  // Remove any existing error message to avoid duplicates
  var existingError = age.parentNode.querySelector("h4.error-msg");
  if (existingError) {
    existingError.remove();
  }

  if (/[^0-9]/.test(age.value)) {
    var h45 = document.createElement("h4");
    h45.classList.add("error-msg"); // Add a class to identify the error later
    var txttt = document.createTextNode("Bitte geben Sie nur Nummern ein");
    h45.appendChild(txttt);
    // Use the parent node to insert h45 BEFORE the age element
    age.parentNode.insertBefore(h45, age);
    h45.style.color = "red";
    return false;
  } else {
    return true;
  }
}

Key Changes Explained

  • Removed the unnecessary age.parentNode.appendChild(h45); line — we can insert the element directly into its correct spot without adding it first.
  • Called insertBefore() on age.parentNode (the parent of both elements) instead of h45, which correctly places the error message above the input.
  • Added a check to remove any existing error message before creating a new one — this prevents multiple error lines from stacking up if the user triggers the blur event repeatedly.
  • Added a class error-msg to the h4 element so we can easily find and remove it later.

That should fix the error and make your validation message show up exactly where you want it!

内容的提问来源于stack exchange,提问作者alordlord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:31:35