Changing the name of a html class with for loop variable - javascript

I have several of html class's incrementing up in class name such as:
<div class="chicken1">
<b></b>
</div>
<div class="chicken2">
<b></b>
</div>
<div class="chicken3">
<b></b>
</div>
I'm trying to write a for loop which will loop through these class names, adding the index to the end each class name and then calling a function in 2s delays.
for ( var i = 1; i <= 3; i++ ) {
setTimeout(function() {
myFunction(".chicken" + i + " b");
}, 2000 * i);
}
However this isn't working.
Fiddle

The problem is actually that of setTimeout() called within a loop; to do this properly you have to close over the loop variable:
for (var i = 1; i <= 6; ++i) {
setTimeout((function(i) {
return function() {
myFunction(".chicken" + i + " i");
};
})(i), i * 2000);
}
Demo
It uses a function that gets called immediately, passing the value of i; this value is retained until the setTimeout() is fired.

are you using jquery? try
for ( var i = 1; i <= 3; i++ ) {
myFunction($(".chicken" + i + " b"));
}
in jquery, to select elements,class etc. we need $("<selector here>");

This works fine for me:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div class="chicken1">
<b></b>
</div>
<div class="chicken2">
<b></b>
</div>
<div class="chicken3">
<b></b>
</div>
<script>
$( document ).ready(function() {
for ( var i = 1; i <= 3; i++ ) {
$(".chicken"+i+" b").html("Hey " + i);
}
});
</script>
</body>
</html>

Related

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Using setTimeout inside a for loop - not working

I have a setTimeout inside the a for loop, but it not behaving as i anticipated.
I have a bunch of banners in a page that are loading all at once. I am removing their parent's div html and storing it in an array. Then I would like for each parent to receive its corresponding html every 5 seconds. This only needs to happen once on ready state.
Here's my code...
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
for ( var k = 0; k < imgs.length; k++ ) {
var url = $(imgs[k]).html();
$(imgs[k]).html('');
setTimeout(function(y) {
console.log(k * 5000);
$(imgs[k]).html(url);
}, k * 5000, k);
}
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
As you can see the images do not get printed on the screen one at a time every 5 seconds - which I thought I was doing.
Thank you for any help.
Serge
It will be better to simplify your code while you don't need any of variables/arrays outside this function .. you can just use jquery .each()
try This
function oneBanner() {
var divs = $('.banner-slide');
divs.each(function(i){ // loop through .banner-slide divs
var ThisIt = $(this); // define this outside setTimout function
setTimeout(function(){
divs.hide(); // hide all .banner-slide divs
ThisIt.show(); // show just this one
} , 5000 * i); // time * the i -- i is the index of the div
});
}
see the code in action
function oneBanner() {
var divs = $('.banner-slide');
divs.each(function(i){
var ThisIt = $(this);
setTimeout(function(){
divs.hide();
ThisIt.show();
} , 5000 * i);
});
}
oneBanner();
.banner-slide:not(:first){
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
Note: by using setTimeout() you'll show each image for 5 seconds and the code will stop looping
Update up to the OP comment
function oneBanner() {
var divs = $('.banner-slide'),
htmlArray = [];
divs.each(function(i){
var ThisIt = $(this); // get this outside the setTimout
htmlArray.push(ThisIt.html()); // push the inner html to the array
ThisIt.html(''); // emty this div
setTimeout(function(){
$(ThisIt).html(htmlArray[i]); // add html again with setTimeout every 5 second to its parent div
} , 5000 * i);
});
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
one word: closure
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
imgs.forEach(($img,k)=>{
var url = $img.html();
$img.html('');
setTimeout(function(y) {
$img.html(url);
}, k * 5000, k);
})
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
You are referencing the wrong variable inside of your setTimeout. Replace 'y' with 'k'
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
for ( var k = 0; k < imgs.length; k++ ) {
var url = $(imgs[k]).html();
$(imgs[k]).html('');
setTimeout(function(k) {
console.log(k * 5000);
$(imgs[k]).html(url);
}, k * 5000, k);
}
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>

Can I use for loop with onclick to write out multiple results?

Sorry for my English.
A want to write out numbers (0, 3, 6, 9... 27) with the help of a for loop, but it seems it is harder than I thought. Thank You for your help.
I found a similar problem: For loop onclick button
function count() {
var i = 0;
if (i < 10) {
document.getElementById("demo").innerHTML = (i * 3);
} else {
document.getElementById("demo").innerHTML = "nothing";
}
i++;
}
<div>
<h1>This is a Heading</h1>
<h1 onclick="count()"><span>Click on me</span></h1>
<br/>
<p id="demo"></p>
</div>
View on JSFiddle
If I understand correctly, I don't think you need a for loop.
Your current code defines i=0 each time the function is called.
You'll just need to define the i variable outside of your function so it can be properly incremented.
var i = 0;
function count() {
if (i < 10) {
document.getElementById("demo").innerHTML = (i * 3);
} else {
document.getElementById("demo").innerHTML = "nothing";
}
i++;
}
<div>
<h1>This is a Heading</h1>
<h1 onclick="count()"><span>Click on me</span></h1>
<br/>
<p id="demo"></p>
</div>
Alternatively, increment the counter by three upon each click. Below, I'm using the ternary operator. It's saying, "if i is less than 27, add three. otherwise, set it to 'nothing'."
var i = 0,
output = document.getElementById('output');
function increment() {
i = i < 27 ? i + 3 : 'nothing';
output.innerHTML = i;
}
document.getElementById('trigger').addEventListener('click', increment);
<h1 id="trigger">Click on me</h1>
<p id="output">0</p>
How about something like that:
function count() {
for (i=0; i<10; i++) {
document.getElementById("demo").innerHTML += (i * 3)
}
}

How to add images (a splitted string in array with .png string concat in each index) in the same div in which script is entered

I am trying to extract everything before the ',' comma. and replace it with a same name image.in a different divs. how can i create a div element dynamically and add all images passed in it and then add this div inside the div with class name slidepop. i want to have different div with classname slidepop and attend div inside it every time. in below code the slidepop div should be open .
here is my codes:
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
var imagesHtml = '';
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
imagesHtml = imagesHtml + '<img src="/images/' + arrayOfStrings[i] + '.png" />'
}
}
var newDiv = $("<div></div>");
newDiv.append(imagesHtml);
$(".slidepop").append(newDiv);
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>
I have answered the previous similar question posted by you yesterday. And I have looked into the problem again and think your problem can be solved by using global variable in Javascript.
As your problem was that you have multiple divs with class name 'slidepop' and you want to pass different string to split and populate images in the very div in which the script is called.
I have solved the problem like this.
<html>
<head>
<script>
counter = 0;
function splitString(stringToSplit, separator, div) {
var arrayOfStrings = stringToSplit.split(separator);
var imagesHtml = '';
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
imagesHtml = imagesHtml + '<img src="/images/' + arrayOfStrings[i] + '.png" />'
}
}
$.each($('.slidepop'), function(index){
if(index === counter){
$(this).append(imagesHtml);
counter++;
}
});
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',') </script>
</div>
<div class="slidepop">
<script> splitString(',brickfast2,travel insurance2,guide2,sim cart2,tour2',',') </script>
</div>
</body>
</html>
In your script tag I defined a global variable named counter and initialized it with 0.
Now what my written script will do that it will split the passed string same as before. But it will then find all the divs in which class name is slidepop. Now it traverse through each div with $.each() method and when it finds that the index (div no) that is same as counter, it will append the images in that very div. So whenever your splitString() function is called, it will increment the counter (global variable) by 1 so that the function will know that the next images to be placed in next div with class name slidepop
Your question is really confusing!!
Here is what I figured you would want to do.
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
var imagesHtml = '';
var newDiv = "<div></div>";
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
imagesHtml = '<img src="/images/' + arrayOfStrings[i] + '.png" />'
newDiv.append(imagesHtml);
}
}
$(".slidepop").append(newDiv);
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>

Jquery "for" loop to find how many children

I am trying to alert how many children are in a div with the class ".child". Ex: There are five ".child" inside of a div. I am not sure why my for loop to do this doesn't work, and I realize there are better ways but I am practicing for loops. Thanks. The problem can be found here http://jqexercise.droppages.com/#page_0013_
for (var i = 1; i < 100; i++){
if($(".child:nth-child(i)") == true){
}
else {
alert(i);
break;
}
}
You can get number of .child in a div like following.
var num = $('div').find('.child').length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
</div>
Update: If you want to use for loop then you can do it like below using jquery eq() function.
for (var i = 0; i < 100; i++) {
if ($('.child').eq(i).length) {
}
else {
alert(i);
break;
}
}
You used i as string. Using nth-child() do it like below.
for (var i = 1; i < 100; i++) {
if ($(".child:nth-child(" + i + ")").length) {
}
else {
alert(i-1);
break;
}
}
Another way:
alert($('div .child').length);
i inside if condition is a string, not a variable, do this :
if ( $( ".child:nth-child(" + i + ")" ) == true )
var intChildrenCount = $("div .child").length;
var arrChildren = $("div .child");
$.each(arrChildren,function(){
// Here you will get child's HTML one by one
console.log($(this).html());
});

Categories

Resources