horin
horin

Reputation: 1662

My javascript for loop is not working

I have the folowing code:

var transitionsSettingsClass = document.getElementsByClassName("transitionsSettings");  
var transitionsSettingsClassLenght = transitionsSettingsClass.length;  
for (i=0; i < transitionsSettingsClassLenght; i++);   
{   
    transitionsSettingsClass[i].setAttribute("data-transition",transitionsSettings);    
};  

I know that transitionsSettingsClassLenght = 6 because I have checked it with alert. But when I put an alert inside cycle then it shows only 1-time (it should show 6-times). An also attribute data-transition is not set. But when I replace "i" inside transitionsSettingsClass[i] with transitionsSettingsClass[0] my first element changes and it is working. This script is supposed to change attribute data-transition in 6 elements.

Upvotes: 0

Views: 1749

Answers (4)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Remove the ; at the end of

for (i=0; i < transitionsSettingsClassLenght; i++);   

The for here only commands the code before the ;, that is nothing.

I'd recommend you to use the most frequent javascript style, as explicited by Google, as it helps avoid this kind of errors.

Upvotes: 8

Sharath
Sharath

Reputation: 65

The code below is interpreted as follows:

for (i=0; i < transitionsSettingsClassLenght; i++);
{
transitionsSettingsClass[i].setAttribute("data-transition",transitionsSettings);
};

The first line:
for (i=0; i < transitionsSettingsClassLenght; i++);
is executed 6 times as Javascript thinks its a single statement. Then it encounters

{
transitionsSettingsClass[i].setAttribute("data-transition",transitionsSettings);
};

which is executed once as a block. Removing the ; from the end of the for loop will solve the problem.

Upvotes: 0

jAndy
jAndy

Reputation: 235962

Just as a sidenote:


In all modern browsers you can set data- attributes by calling

node.dataset.transition = transitionsSettings;

Upvotes: 0

hjuster
hjuster

Reputation: 4070

Have you tried with jquery each method?

 $('.transitionsSettings').each(function(index) {
        $(this).setAttribute("data-transition",transitionsSettings);
    });

Upvotes: 0

Related Questions