How to Control appendChild behaviour in javascript/jquery? -


we know whenever appendchild child keep on appending. question how can control append child append once, twice, 3 times or number of specified times. i'll give example below, i'm sure you'll know i'm talking about. jquery or javascript answer appreciated. thanks.

jquery, pure javascript

$( document ).ready(function() {      $('#mybtn').click(function(){         $('p:eq(1)').css('background-color', 'yellow');         var newdiv = document.createelement('div');         newdiv.id = "newdiv";         $('#mydiv').append(newdiv);          newdiv.style.height = "25px";          newdiv.style.width = "25px";          newdiv.style.border = "2px solid blue";     });  }); 

html

<div id="container">     <div id="mydiv"></div>      <p>first paragraph</p>     <p>second paragraph</p>     <p>third paragraph</p>      <input type="button" id="mybtn" value="click me" /> </div> 

i switched jquery (smaller). limit 4 divs

jsfiddle: http://jsfiddle.net/trueblueaussie/9f353/

$( document ).ready(function() {      $('#mybtn').click(function(){         $('p:eq(1)').css('background-color', 'yellow');         var count = $(".newdiv").length;         if (count < 4)         {             var $newdiv = $('<div>').attr("id", "newdiv" + count).addclass("newdiv").css({ height: "25", width: "25", border: "2px solid blue"});              $('#mydiv').append($newdiv);         }     });  }); 
  • it uses newdiv class identify items added.
  • it uniquely id's each div added newdivnn

the newdiv class not needed, can count children under mydiv. 1 hides button when reaches required limit:

jsfiddle: http://jsfiddle.net/9f353/1/

$(document).ready(function () {      $('#mybtn').click(function () {         $('p:eq(1)').css('background-color', 'yellow');         var count = $("#mydiv").children().length;         if (count == 3) {             $('#mybtn').hide();         }         var $newdiv = $('<div>').attr("id", "newdiv" + count).css({             height: "25",             width: "25",             border: "2px solid blue"         });         $('#mydiv').append($newdiv);     }); }); 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -