Add Class (odd And Even) In Html Via Javascript?
I have this code example:
Solution 1:
I am not sure really what you want to do.I hope This will help you.
let article = document.querySelectorAll('.post');
article.forEach((item, index) => {
(index % 2 == 0) ?item.classList.add('odd'):item.classList.add('even')
});
Solution 2:
I'm not sure what you really want to do but very probably you don't need have any javascript you can write styles for odd and even childrens.
.post:nth-child(odd) {
color: green;
}
.post:nth-child(even) {
color: red;
}
<sectionclass="timeline"><articleclass="post ">Article</article><articleclass="post ">Article</article><articleclass="post ">Article</article><articleclass="post ">Article</article></section>
Solution 3:
The answer of Czlowiek is in my opinion the best answer, because it does not require Javascript to be enabled.
Next is that you should use ids. It is certainly a logical attribute for sections, but it is also very logical for articles. But if you would like to do this with Javascript, then should you first get a handle on the section tag, with for instance:
var sec = document.getElementById('timeline');
Next can you loop through the childNodes of the section like:
var cntArticle = 0;
for(var i = 0; i < sec.childNodes.length; i++) {
if(sec.childNodes[i].tagName === 'ARTICLE') {
if(cntArticle%2 === 0){
sec.childNodes[i].className += ' left';
} else {
sec.childNodes[i].className += ' right';
}
cntArticle++;
}
}
Post a Comment for "Add Class (odd And Even) In Html Via Javascript?"