Bican M. Valeriu
Bican M. Valeriu

Reputation: 328

Add class (odd and even) in html via javascript?

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"

Upvotes: 1

Views: 2589

Answers (4)

Mohammad Nadr
Mohammad Nadr

Reputation: 533

useing css is more easy

.parent .child:nth-child(2n){
color :red
}
.parent .child:nth-child(2n-1){
color :blue
}
<div class="parent">
<p class="child">hello world</p>
<p class="child">hello world</p>
<p class="child">hello world</p>
<p class="child">hello world</p>
</div>

Upvotes: 0

Md ishtiyaque
Md ishtiyaque

Reputation: 41

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')
});

Upvotes: 3

Loek Bergman
Loek Bergman

Reputation: 2195

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++;
    }
 }

Upvotes: 0

Człowiek Fin Śpiewak
Człowiek Fin Śpiewak

Reputation: 259

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>

Upvotes: 1

Related Questions