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:
- First, you run
age.parentNode.appendChild(h45);— this adds your new<h4>element after theageinput (sinceappendChildplaces elements at the end of the parent's child list). - Then you try
h45.insertBefore(h45, age);— this is where things go wrong! TheinsertBefore()method belongs to the parent node, not the new element you created. When you call it onh45, JavaScript thinks you're trying to inserth45as a child of itself (beforeage), 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()onage.parentNode(the parent of both elements) instead ofh45, 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-msgto 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
相关产品推荐
相关产品推荐

