简体   繁体   中英

here to insert element using jQuery

I want to insert a div inside the div having id = newDiv when the <button class="songBtn btn"><i class="fa fa-play fa-lg playbtn"></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 class="row border-bottom g-3  player-song-detail">
    <div class="col-md-1 col-2 my-auto text-center">
      <!-- play button -->
      <button class="songBtn btn"><i class="fa fa-play fa-lg playbtn"></i></button>
      <input type="text" value="Song Title" placeholder="write song title here" hidden>
    </div>
    <div class="col-md-4 col-8 my-auto" id="newDiv">
      <!-- div should be inserted here -->
    </div>       
  </div>

here is my jQuery code

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

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 class="row border-bottom g-3 player-song-detail"> <div class="col-md-1 col-2 my-auto text-center"> <!-- play button --> <button class="songBtn btn"><i class="fa fa-play fa-lg playbtn"></i>btn</button> <input type="text" value="Song Title" placeholder="write song title here" hidden> </div> <div class="col-md-4 col-8 my-auto" id="newDiv"> <!-- div should be inserted here --> </div> </div>

 $('.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 class="songBtn btn">this is the button</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM