0

I am trying to generate divs with Javascript dynamically. What I mean: in the first div there will be a button with a .click event and when it will be clicked I want a new div to be generated. Inside the new div there must be another button with a .click event which will act as the first one. My problem is that in the div that is generated that button does not create a new div.

This is my js function:

$(function() {
        $('#openFirstTab').click(function(){
            var newDiv = $('<div class="col s4 bordered"><h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5><button id="openSecondTab">Add Div</button></div>');
          $('.row').append(newDiv);
        });
        $('#openSecondTab').click(function(){
            var newDiv = $('<div class="col s5 bordered"><h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5><button id="openSecondTab">Add Div</button></div>');
          $('.row').append(newDiv);
        });
    });

and the HTML:

<div class="custom_container-full-width">
    <div class="row">
      <h1 class="header center orange-text">Starter Template</h1>
        
      <div class="col s3 bordered">  
        <h5 class="header col s12 light">A modern responsive front-end 
             framework based on Material Design</h5>
        <button id="openFirstTab">Add Div</button>
      </div>
    </div>  
  </div>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • instead of `$('#openSecondTab').click(function(){` use `$(document.body).on("click", "#openSecondTab" function(){` – Luis felipe De jesus Munoz Apr 16 '18 at 14:04
  • The issue is that when you call `$('#openFirstTab').click` it only applies to the elements that *exist at that time*. As you create some new elements, the connection of the element->event has already been completed, so does not apply to the new element/button. So you need to use *event delegation*. As explained in the duplicate link. – freedomn-m Apr 16 '18 at 14:10
  • 1
    Also, `id`s must be unique, so still wouldn't work even if the buttons were created on initial render/load - as it would only wire to the first one. Use a class instead of an id. – freedomn-m Apr 16 '18 at 14:11

0 Answers0