Add CSS Class after HTML div using JQuery

3.4k views Asked by At

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!

3

There are 3 answers

1
user2736012 On BEST ANSWER

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'});
0
raina77ow On

How about this:

var $box = $('<div/>').addClass('rectangle');

... or as simple as...

var $box = $('<div class="rectangle"/>');

Actually, I might consider preparing this item first-hand, then just cloning it. For example:

var $boxTemplate = $('<div class="rectangle">');
function addDiv($ele) {
   $boxTemplate.clone().insertAfter($ele);
}
0
hagbard On

change the var $box line to:

var $box = $('<div class="rectangle" />');