Reputation: 1393
I am trying to use the code bellow to add dynamic divs with some attributes but the code doesnt work.
<div id="divsholder"></div>
var num = "4";
var container = $('<div />');
for(var i = 1; i <= num; i++) {
container.append('<div id="mystyle" class="pic'+i+'" />');
}
$('#divsholder').html(container);
Any ideas?
Upvotes: 0
Views: 3631
Reputation: 6318
Try something like this using jQueries "APPEND
" function
Check my fiddle: http://jsfiddle.net/somdow/9A6DA/2/
With this example, i made it so that when the p tags reach 4, for it to alert the user. You can add whatever you want to happen after the 4th event etc.
css:
#mainW{width:200px; background:#f00; text-align:center;}
.blu{ background-color:blue; }
html:
<div id="mainW">
<a href="#"> content here,</a><br/>
</div>
here is the code required for the jsfiddle. js/jq
$('#mainW a').click(function(){
$('#mainW').append( "<p>Test</p>" );
if( $('p').length == 4 ){ alert("lopan")}
});
Upvotes: 2
Reputation: 12707
Your code works fine, but the ending HTML results into the following:
---divsholder----------------------
| |
| -- a div with no name ------ |
| | | |
| | --divs from for loop-- | |
| | | | | |
| | | | | |
| | ---------------------- | |
| | | |
| --------------------------- |
| |
-----------------------------------
So the problem might arise from the fact that you are placing the divs
into another div un-intentionally.
I have modified your code so that you can clearly see the problem visually here
Upvotes: 0
Reputation: 933
Your code working perfect
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="divsholder"></div>
<script>
$(document).ready(function(){
var num = "4";
var container = $('<div />');
for(var i = 1; i <= num; i++) {
container.append('<div id="mystyle" class="pic'+i+'" />');
}
$('#divsholder').html(container);
});
</script>
</body>
</html>
Code result
<div id="divsholder"><div><div id="mystyle" class="pic1"></div><div id="mystyle" class="pic2"></div><div id="mystyle" class="pic3"></div><div id="mystyle" class="pic4"></div></div></div>
ID element maybe one and unique. If you use more than one ID use class="class-name"
Upvotes: 1