Reputation: 23
I want to append the data only into a specific ID myID
. It only prints the last value of the loop which is 3
.
setInterval(sample, 2000);
function sample()
{
for(var i=0;i<=3;i++)
{
$('.found .find').each(function() {
if(this.id == "myID")
{
// if the ID of this element is equal to #myID
// this is the place where the data will append
$(this).empty();
$(this).append(i);
}
});
}
}
HTML:
<div class="found">
<div class="find" id="myID"></div>
</div>
<div class="found">
<div class="find" id="anID"></div>
</div>
<div class="found">
<div class="find" id="anID2"></div>
</div>
Upvotes: 0
Views: 1047
Reputation: 23
$(function() {
setInterval(loop, 1000);
function loop() {
$(".found").find(".find[id*=ID]").empty();
for(var i=0;i<=3;i++)
{
$(".found").find(".find[id*=ID]").prepend(i);
}
}
});
Upvotes: 0
Reputation: 2254
Modified the code as You want it to happen just once Run the original code if you want to keep doing it
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="found">
Hello World
</div>
<div class="found">
<div class="find" id="myID"></div>
</div>
<div class="found">
<div class="find" id="anID">Append here</div>
</div>
<div class="found">
<div class="find" id="anID2"></div>
</div>
<script>
$(document).ready(function(){
//$('#anID').empty();
for(var i=0;i<=3;i++)
{
$('<p>'+i+'</p>').appendTo('#anID');
//$('.found').append(i);
//$('.found').append("\n");
}
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 1
Try
$(function() {
setInterval(loop, 1000);
function loop() {
var n = "0123";
for(var i=0;i<=3;i++) {
$(".found").find(".find[id*=ID]").html(n);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="found">
<div class="find" id="myID"></div>
</div>
<div class="found">
<div class="find" id="anID"></div>
</div>
<div class="found">
<div class="find" id="anID2"></div>
</div>
Upvotes: 0
Reputation: 48257
empty
removes all children from the given element, so you probably want to use it before the loop:
$('.found').empty();
for (var i=0; i <= 3; i++) {
$('.found').append(i);
}
This will empty out the container, then append your list of elements (or numbers).
This can be used in an MVC framework's render
method to empty the container of the previous render before adding new content.
Upvotes: 3