It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using

element1.parentNode.insertBefore(element2, ...)
would be the solution. However, it is not working as expected and instead, an error is being thrown.

(function() {
    let containers = document.querySelectorAll('.field-container');
    let hr = document.createElement('hr');
    containers[0].parentNode.insertBefore(containers[1], hr);
})();
 

<div>
    <div class="field-container">
        <input placeholder="Field 1" type="text">
        <span></span>
    </div>
    <div class="field-container">
        <input placeholder="Field 2" type="text">
        <span></span>
    </div>
</div>

Adding the hr tag directly to the parent element before trying to insert it between the containers resolves the error. However, the insertion then occurs at the end rather than between the two elements.

(function() {
    let containers = document.querySelectorAll('.field-container');
    let hr = document.createElement('hr');
    containers[0].parentNode.appendChild(hr);
    containers[0].parentNode.insertBefore(containers[1], hr);
})();
 

<div>
    <div class="field-container">
        <input placeholder="Field 1" type="text">
        <span></span>
    </div>
    <div class="field-container">
        <input placeholder="Field 2" type="text">
        <span></span>
    </div>
</div>

Answer №1

insertBefore(newElement, referenceElement)
In this scenario, the hr element should be placed before the containers[1]
where newElement represents the hr to be inserted, and the referenceElement is the containers[1] which acts as the point of insertion.

(function() {
    let containers = document.querySelectorAll('.field-container');
    let hr = document.createElement('hr');
    // containers[0].parentNode.appendChild(hr); this line is unnecessary
    containers[0].parentNode.insertBefore(hr, containers[1]);
})();
<div>
    <div class="field-container">
        <input placeholder="Field 1" type="text">
        <span></span>
    </div>
    <div class="field-container">
        <input placeholder="Field 2" type="text">
        <span></span>
    </div>
</div>

Answer №2

Feedback:

  1. The issue lies in the order of code execution. Instead of insertBefore(containers[1], hr), try using insertBefore(hr, containers[1])
  2. Additionally, make sure you are adding two <hr> elements instead of moving just one
  3. See below for a more organized solution

Updated JavaScript Solution:

(function() {
    const [ firstChild, secondChild ] = document.querySelectorAll('.field-container');
    const parent = firstChild.parentElement;
    parent.appendChild( document.createElement('hr') )
    parent.insertBefore( document.createElement('hr'), secondChild );
})();

Answer №3

No need to overcomplicate things with JavaScript, just utilize CSS

:root{
  --space:20px;
}
.field-container{
  margin:var(--space);
  position:relative;
  width:min-content;
}

.field-container:not(:last-child)::after{
  content:'';
  position:absolute;
  bottom: calc(var(--space)* -1 / 2);
  left:0;
  width:100%;
  border-bottom:2px solid grey;
}
<div class='container'>
    <div class="field-container">
        <input placeholder="Enter text here" type="text">
        <span></span>
    </div>
    <div class="field-container">
        <input placeholder="Enter text here" type="text">
        <span></span>
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When I click on the event target, it selects the button within the span. What is the next step I should take

I have a button element that contains a span, and I want to extract the value associated with the button when it is clicked. However, if I click on the span inside the button, I am unable to retrieve the desired value because the event target points to the ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

when a div contains another div and is then followed by another div, apply the following style

Is there a way to create a rule that functions like the following: .container .unit:first-child(if it contains div.box1.extra) + .box2 { top: 50px;} <div class="container"> <div class="unit"> <div class="box1 extra"><!-- co ...

Enhancing the visual appeal of HTML code in "view Source" by injecting it using a System.Web.UI.WebControls.Literal

I am currently placing code within a literal in the following manner. ImageItem.Text = string.Format("<div class=\"thumb\"><img src=\"{0}\" width=\"132\" height=\"99\" /><a class=\"more\"> ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

Using select2, items can be automatically selected for an ajax call

Is it possible to configure a select2 control to automatically select an item when the ajax response contains extra data? I am looking to set up my controller to mark an item as an exact match in the JsonResult and have the select2 control automatically s ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

React's createPortal function does not place the child element inside a container

My new to-do list app in React has a simple functionality where clicking a button should add a new item to the list. However, I am facing an issue with the createPortal method not triggering the UI to render the new item. Here's the code snippet causi ...

I'm new to this, but can someone explain why I'm being redirected to the register_db.php page when I click on the register button?

Why when I click the register button, it redirects me to the register_db.php page instead of sending the data to the database and keeping me on the same register.php page? I want the data to be sent to the database without changing the webpage. register.p ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

NextJS build problem causing all content to become static

As a newcomer to NextJS with prior experience in basic React apps, I recently attempted to deploy a CRUD NextJS app (utilizing prisma and mongoDB). Everything runs smoothly with npm run dev, but issues arise when transitioning to npm run build followed by ...

Creating a function that counts the number of times a button is clicked

I want to have the "game" button appear after the user clicks the "next-btn" 2 times. Once the multiple choice test has been completed twice, I'd like the game button to show up and redirect the user to a separate HTML page called "agario.html." I&ap ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

Ensure accurate detection of invalid values for SVG Elements in React using jest testing framework

When testing my react app, I am attempting to capture any errors that are thrown or logged to the console. If a regular HTML element such as <p> contains invalid attributes like <p color={false}></p>, react will display an error via cons ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Using local variables in NodeJS callbacks

Despite the abundance of information on SO, I have yet to find a suitable answer to my particular situation. The following code snippet is causing me issues: for(var i=0; i < shop.collections.length; i++){ if(!shop.collection[i].active){ var dat ...

Jquery refuses to conceal a particular element

I've encountered this issue before, but I'm facing a problem this time. I'm attempting to create a popup that is initially hidden. When clicked, the popup does appear, but I'm unable to close it. Additionally, when trying to change the ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...