Add HTML to the nearest div containing a specific class when a button is clicked using JavaScript and jQuery

Here is the HTML setup I'm working with:

<div class='form-row'>
    <div class='col-2'>
        Blah Blah
    </div>
    <div class='col-4'>
        <button type='button' class='add_row'>+</button>
    </div>
</div>

When the add_row button is clicked, I want to add another form-row div right next to the closest existing form-row div. The end result should look like this:

<div class='form-row'>
    <div class='col-2'>
        Blah Blah
    </div>
    <div class='col-4'>
        <button type='button' class='add_row'>+</button>
    </div>
</div>
<div class='form-row'>
    <div class='col-2'>
        Blah Blah
    </div>
    <div class='col-4'>
        <button type='button' class='add_row'>+</button>
    </div>
</div>

I attempted to use jQuery with the following script:

$(document).on('click', '.add_row', function () {

    $(this).closest('.form-row').append("<div class='form-row'>div contents</div>");

 });

However, it ends up adding the new div AFTER the direct parent of the button (<div class='col-4'>).

What would be the correct jquery code to append the new div to the closest div with a specified class instead?

Answer №1

If you're looking to include a sibling in the form-row, rather than its content, you have the option of using either insertAfter() or after().

$(document.body).on('click', '.add_row', function (e) {
  $(e.target).closest('.form-row').after('<div class="form-row">Content</div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form-row'>
  <div class='col-2'>
    Blah Blah
  </div>
  <div class='col-4'>
    <button type='button' class='add_row'>+</button>
  </div>
</div>
<div class='form-row'>
  <div class='col-2'>
    Blah Blah
  </div>
  <div class='col-4'>
    <button type='button' class='add_row'>+</button>
  </div>
</div>

Answer №2

slight modification in your code

$(document).on('click', '.add_row', function (e) {
  $(this).closest('.form-row').clone().insertAfter($(this).closest('.form-row'));
});

Answer №3

update: make use of $(el).after() as recommended by @Taplar. See modified code below


When utilizing $(el).append(...), you are actually appending within $(el). The desired action should be to append to the parent of $(el), which is represented by $(el).parent().

$(function() {
  $(document).on('click', '.add_row', function () {

  $(this).closest('.form-row').after("<div class='form-row'>div contents</div>");
 });
});

If your intention is to duplicate the .form-row, it is necessary to clone it before performing the append operation.

$(function() {
  $(document).on('click', '.add_row', function () {
    const $formRow = $(this).closest('.form-row');
    $formRow.parent().after($formRow.clone());
  });
});

For reference, here is the Vanilla JavaScript equivalent:

const $formRow = document.querySelector('.form-row');

document.onclick = (e) => {
  if (!e.target.classList.contains('add_row')) return;
  $container.after($formRow.cloneNode(true));
};

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

What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop. So, ...

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

I am looking to implement a Mouseover effect on my Canvas element using JavaScript

To create a mouseover effect only on a specific canvas location, I have developed the MousePosition function (as seen below). The commands for the mouseover effect should be implemented within the MouseOverButton function. However, despite my efforts, it ...

Turning off the ability to horizontally scroll in an iframe using touch controls

I am trying to disable horizontal scrolling in an iframe on my website, particularly when a user uses touch input and drags horizontally. The scroll bars can still be visible and draggable when touched directly. Unfortunately, I do not have control over th ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

Issues with JavaScript PHP Ajax request

I am currently developing a Single Page Application and facing challenges with Ajax. The two files I am working with are bhart.js and RespSelArt.php. However, my Ajax Call is not functioning as expected. At this point, all I want is to display "worked". H ...

Tips for adjusting the width of a div when printing

Imagine I have two container elements named container1 and container2. First, I assign a width of 30% to container1 and 60% to container2. Then add a border between the two containers. However, when I attempt to print, container1 takes up the full 100% o ...

Vue.js: Incorporating a client-side restful router using vue-router and a state manager

Trying to set up a client-side restful api with vue.js and vue-router where route params can be utilized to showcase a subset of a store's data into components. All the necessary data for the client is loaded into the store during initialization (not ...

Using justify-content-between in a div container with only two items will not produce the desired effect

I'm having trouble aligning two elements on opposite ends of a div container using Bootstrap's justify-content-between class. The h4 element is not on the left and the button on the right as expected. I am using Bootstrap 5.2.3. Can anyone help m ...

A Guide on Accessing Promise Results in AngularJS

In my code, I am using a controller to retrieve information from SharePoint. While debugging, I noticed that the value of data.d.UserProfileProperties.results[115].Value is what I need to display in the view. However, I am struggling to extract that value ...

The HTML checkbox appears disproportionately large on the user's screen when using Firefox and Chrome, but not when using Internet Explorer

There seems to be a strange issue that I've come across. One of our QA tester's computers is displaying an HTML checkbox in a very large size when using Firefox and Chrome, but it appears normal in size when viewed in IE. Meanwhile, on my comput ...

Utilizing PHP to create a loop that processes two submitted forms

Is my code handling two submit forms in a loop correctly? I am facing an issue with the second form where it redirects to selectedSold.php but does not display any details or retrieve the name="nganga" of the selected row. The first form works fine, so I c ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

codeigniter jquery ajax form submission issue, works in all cases except when integrated

Recently, I experimented with submitting a form via jQuery ajax without using CodeIgniter in order to better understand how ajax functions. Everything seemed to work smoothly, but now I want to implement the same functionality within my CodeIgniter applica ...

Similar to utilizing remote_function with the help of jquery and jquery-rails

Currently, I am in the process of developing an application using Rails 3.0.3 and Ruby 1.9.2. To leverage jQuery instead of prototype, I have incorporated the jquery-rails gem into my project. The challenge I am facing pertains to a .js.erb file that is ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Gain entry to Zurb Foundation for Apps modules within your AngularJS application

Currently, I am developing an AngularJS application utilizing Foundation for Apps. One key element in my layout is a Foundation Apps panel that serves as the top menu. <div zf-panel="" id="topMenu" position="top" class="panel-fixed">...</div> ...

How can we ensure that the load more button disappears at the appropriate moment in this Vue 3 application?

I have been developing a news application with Vue 3 and the News API. I am currently implementing a feature for loading more articles on the page. Initially, there are 24 articles displayed, and if there are more articles available than the current numbe ...

Setting the default value for a useRef<HTMLInputElement> in ReactJs with Typescript

Is there a way to assign a number as the initial value on useRef<HTMLInputElement> without using useState<number>() since the field is a simple counter? Below is my TypeScript code: const MyComponent = () => { const productAmountRef = us ...

Error in processing JSON data due to numerical discrepancy

Recently, I have been working with a PHP class that uses AJAX to return data in JSON format. Here is an example of the data it returns: ["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"] However, when I try to use jquery.parseJSON(data), I'm enco ...