Javascript whitespace issue
In my container news-variety
I got 4 columns, I just want to take all column in to left and animate each column to write.
For that I use the开发者_运维百科 CSS left
property.
I wrote the function to get the no. of column, but it adds whites space and display wrongly, in my case I need the i
value 0,1,2,3,4
but this function shows 0, 2, 4, 6, 8
.
Please help me to remove the whites space and get the i
value to 0,1,2,3,4
.
This is my code :
var newsVariety = document.getElementById('news-variety');
if(newsVariety){
var newsColums = newsVariety.childNodes;
for(i=0;i<newsColums.length;i++){
if(newsColums[i].className == "column") continue;
alert(i);
}
}
You're getting whitespace (text) nodes in addition to elements. You could exclude the text nodes like this:
var newsVariety = document.getElementById('news-variety');
if(newsVariety){
var newsColums = newsVariety.childNodes;
for(i=0;i<newsColums.length;i++){
if(newsColums[i].className == "column") continue;
if(newsColums[i].nodeType == 3) continue;
alert(i);
}
}
but a better solution would be to use a function (getElementsByTagName) that only gives you elements in the first place, like this:
var newsVariety = document.getElementById('news-variety');
if(newsVariety){
var newsColums = newsVariety.getElementsByTagName('whatever-your-element-tag-is');
for(i=0;i<newsColums.length;i++){
if(newsColums[i].className == "column") continue;
alert(i);
}
}
You are forgetting that whitespace is represented in the DOM as text elements.
if (newsVariety) {
var newsColums = newsVariety.childNodes;
for (col = 0, i = 0; i < newsColums.length; i++) {
if (newsColums[i].className == "column")
continue;
alert (col++);
}
}
精彩评论