Reputation: 351
I tried this javascript function before adding a.className = "year";
and everything worked properly, but then, adding it, I couldn't get the page to load neither with Safari nor Google Chrome. What I need to do is just add a class to the new a
element, I tried also with a.setAttribute("class", "year");
but I got the same error: the page wouldn't load.. If someone knew how to help me I would be very grateful!
function create_timeline() {
timeline = document.getElementById("timeline_ul");
years = document.getElementsByClassName("year");
for (i=0;i<years.length;i++) {
if (years.item(i).nodeType==1) {
year = years.item(i).innerHTML;
a = document.createElement("a");
a.innerHTML = year;
a.className = "year";
timeline.appendChild(a);
}
}
}
Upvotes: 0
Views: 901
Reputation: 18522
but I got the same error: the page wouldn't load..
the problem is, your code runs in a infinite loop. The reason for that is:
With the call below you've fetched all elements with class "year". The collection that is returned is a dynamic collection
years = document.getElementsByClassName("year");
while iterating through the collection, you are creating new anchor elements, and setting them the "year" class.
When you append them to the document, they will be automagically added to the collection created 1st step, because it is a dynamic collection, because new elements match the "subject" (here the class "year") of the collection.
to avoid infinite loops, you have many possibilities.
cache the length property in a variable
var i=0, len = years.length;i<len;i++
but with this approach, you cannot be sure whether new elements are appended to the collection or added in some "logical" or "random" order.
Convert the collection to a JavaScript array
years = document.getElementsByClassName("year");
years = Array.prototype.slice.call(years, 0);
or use document.querySelectorAll, which returns a static collection of elements.
years = document.querySelectorAll('.year');
I would go for approach #2 or #3.
Upvotes: 1