Home > Mobile >  here to insert element using jQuery
here to insert element using jQuery

Time:01-28

I want to insert a div inside the div having id = newDiv when the <button ><i ></i></button> is clicked. How can I do this with jQuery? I'm using after() but it only inserts the div after the button. actually, I want to do this dynamically as there could be multiple sections like this here is my HTML code

<div >
    <div >
      <!-- play button -->
      <button ><i ></i></button>
      <input type="text" value="Song Title" placeholder="write song title here" hidden>
    </div>
    <div  id="newDiv">
      <!-- div should be inserted here -->
    </div>       
  </div>

here is my jQuery code

 $(".songBtn").click(function(){ 
          $( this ).after( "<div>Test Div</div>" ); 
});

CodePudding user response:

use append instead of after

 $(".songBtn").click(function(){ 
          $( "#newDiv" ).append( "<div>Test Div</div>" ); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    <div >
      <!-- play button -->
      <button ><i ></i>btn</button>
      <input type="text" value="Song Title" placeholder="write song title here" hidden>
    </div>
    <div  id="newDiv">
      <!-- div should be inserted here -->
    </div>       
  </div>

CodePudding user response:

$('.songBtn').click(function(){
  $('#newDiv').append('<div></div>');
})
#newDiv{
  border:1px solid red;
}
#newDiv div{
  background:orange;
  border:1px solid red;
  width:10px;height:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newDiv">This is div with ID newDiv</div>
<button >this is the button</button>

  •  Tags:  
  • Related