webmasternewbie webmasternewbie -4 years ago 79
Javascript Question

JS - iterating over array and add new numeric for if statement

Lets assume I got some king of array... or for simplicity links.

HTML:

<a href'myspecialPath'></a>
<a href'myspecialPath'></a>
<a href'otherPath'></a>
<a href'otherPath'></a>
<a href'myspecialPath'></a>
<a href'myspecialPath'></a>


JS:

var test = document.getElementsByTagName('a');
var testLength = test.length;

for (i=0; i<testLength; i++){
if (test.getAttribute('href').indexOf('myspecialPath') !== -1){
//we list here every link with special patch
// and I want it to have new numeration, not:
link[i] have myspecialPath! // 1,2,5,6
// cause it has gaps if link don't have special path - 1,2,5,6
// and I want it to have numeric like 1,2,3,4
}
else{
link[i] without myspecialPath! // 3,4... and I want 1,2
}
}


I hope everything is clear. I want to number link following from 1 [i+1] to the end without gaps.

EDIT:
I did try [y+1] before but thanks to @American Slime the answer is:

y = 0;
for (i=0; i<testLength; i++){
if (test.getAttribute('href').indexOf('myspecialPath') !== -1){
links:[y ++] have myspecialPath! // 1,2,3,4... and so on, OK - it's working fine!
}
}


anybody fell free to correct this question/answer to better describe the problem.

Answer Source

I'm pretty sure this is what you're asking...

var links = document.querySelectorAll('a');
var count = 1;

for (var i = 0; i <= links.length-1; i++) {

    if (links[i].getAttribute('href') === 'myspecialPath') {

        links[i].setAttribute('href', 'myspecialPath' + count);
        count++;

    };

};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download