Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  13] [ 7]  / answers: 1 / hits: 19516  / 11 Years ago, wed, october 9, 2013, 12:00:00

I'm trying to update a set of divs class=oct_days to give them id based on :nth-child(n). The format of the id is oct_n. I'm trying to accomplish this using a for loop to set this for divs.



window.onload = function addOctDate() {
var cls = document.getElementByClass(oct_days);
for (var n = 1; n < 32; n++) {
cls[n].id = oct_ + n;
}
};


Fiddle (http://jsfiddle.net/ascottz/D9Exm/)



The idea is to have .oct_days:nth-child(1) have id=oct_1, but id isn't being set.


More From » for-loop

 Answers
67

clsyour issues are this:




  1. window.onload was being run before your html was initialized

  2. you need to call document.getElementsByClassName not

  3. you are starting your iteration at 1, indexes are 0 based and you should start there and add the + 1 as noted below

  4. also, while iterating, its good to only iterate only over the known items in your list



try this code:



function addOctDate() {
var cls = document.getElementsByClassName(oct_days);
for (n=0, length = cls.length; n < length; n++) {
cls[n].id= oct_ + (n + 1);
}
};

addOctDate()

[#75131] Tuesday, October 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byron

Total Points: 616
Total Questions: 101
Total Answers: 91

Location: Reunion
Member since Wed, Apr 14, 2021
3 Years ago
byron questions
Wed, Jan 26, 22, 00:00, 2 Years ago
Sat, Jun 6, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
Wed, Sep 11, 19, 00:00, 5 Years ago
;