I have this code example:
<section class="timeline">
<article class="post ">
<article class="post ">
<article class="post ">
<article class="post ">
</section>
Now i want to know how to add a class via javascript to article element. For example:
1st article add class "left"
2nd article add class "right"
3rd article add class "left"
4th article add class "right"
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')
});
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; }
<section class="timeline"> <article class="post ">Article</article> <article class="post ">Article</article> <article class="post ">Article</article> <article class="post ">Article</article> </section>
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++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.