Search code examples
javascriptjquerycssclassinsertafter

Add CSS Class after HTML div using JQuery


I have this HTML

            <div class="portItem"></div>
            <div class="portItem"></div>
            <div class="portItem"></div>
            <div class="portItem"></div>

This CSS

 .rectangle {
   height: 250px;
   width: 100%;
   position: relative;
   display: none;
   background: #ffffff;
   box-shadow: 1px 0px 20px black;
   overflow-y: hidden;}

      Here's the CSS for portItem, although not necessary (forms 4 green blocks next to each other)

     .portItem {
       height: 180px;
       width: 250px;
       position: relative;
       display: inline-block;
       background: #D0E182;
        margin: 0 5px 5px 0;

And I'm trying to add the CSS rectangle after any of the portItems that I click on.

Here's the JQuery function I'm trying to use:

 $(document).ready(function() {
   $('.portItem').click(function() {
     addDiv($(this));
   });
 });



 function addDiv($ele) {
   var $box = $('<div />' '.rectangle');
   $box.insertAfter($ele);
 }

The problem is with the var $box statement, I can't get it to work.

Thanks in advance!


Solution

  • You're missing a comma, and an object.

    var $box = $('<div />', {'class':'rectangle'});
    // -------------------^ ^                   ^
    //    added comma-----| |___________________|---and object literal syntax
    

    The quotes around class are needed to support older browsers. You could also use className instead.

    var $box = $('<div />', {className:'rectangle'});