Jquery - if element contains a class, add HTML after element

Viewed 1891

I've got a booking form.booking-wrap with 2 elements in it, div#booking and then div.quantity

<form class="booking-wrap"> 
    <div id="booking"></div>
    /* insert div#message IF div.quantity is present inside div.booking-wrap */ 
    <div class="quantity"></div>
</form>

The div.quantity is only present dynamically for some bookings.

What I am trying to achieve is that if the div.quantity is present, then I would like to insert an additional html div#message, but this new div should appear after div#booking and before div.quantity

I am trying the following jQuery:

if($('.booking-wrap:has(div.quantity)')){
  $('#booking' ) .after( '<div id="message">Message</div>');
}

But that doesn't seem to work.

I then tried this:

$('.booking-wrap:has(div.quantity)').append($('<div id="message">Message</div>'));

This works and the new div appears, however it is just next to the quantity div.

How can I get it to show after the #booking , but before .quantity?

5 Answers

Try using prepend instead of append, since the selector $('.booking-wrap:has(div.quantity) will return the (div.quantity) element.

Example:

$('.booking-wrap:has(div.quantity)').prepend($('<div id="message">Message</div>'));

Any selector returns an object, you should check the length property of the returned object. Like $('.booking-wrap:has(div.quantity)').length

Though, I prefer $('.booking-wrap > div.quantity').length

if($('.booking-wrap > div.quantity').length){
  $('#booking').after('<div id="message">Message</div>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="booking-wrap">
  <div id="booking">booking</div>
  <div class="quantity">quantity</div>
</form>

You can use "hasClass()" jQuery function to check class is exist or not:

Try This

if($( ".booking-wrap" ).children('div').hasClass( "quantity" )){
  jQuery('<div id="message">Message</div>').insertAfter('.booking');
}

Try This jQuery.

if($(".quantity").length ){
    $('#booking' ).after( '<div id="message">Message</div>');
}

You need to put the div you are adding within a function.

        if($('.booking-wrap:has(div.quantity)')){
            $( "#booking" ).after(function() {
                return '<div id="message">Message</div>';
            });
        }
Related