1

I need to insert a class attribute of "odd" or "even" for each paragraph in the HTML displaying using the modulo and ternary operator. I extracted the paragraph element, but I am unsure of how to insert the class and word the code within the ternary operator. I know my code is pretty terrible, but any tips or suggestions would be wonderful.

function oddEven()
{
    var parArray= document.getElementsByTagName("p");

    for(var i=0; i<parArray.length; i++)
    {
        (parArray % 2== 0)? parArray=="even" : parArray=="odd"; 
    }
    //end of oddEven()    
}
bytecode77
  • 14,163
  • 30
  • 110
  • 141
CV88
  • 87
  • 1
  • 2
  • 10

3 Answers3

3

That's easily done with CSS, but if you want to learn JS, here's your example with minimal modifications:

function oddEven() {
  var parArray = document.getElementsByTagName("p");

  for (var i = 0; i < parArray.length; i++) {
    parArray[i].classList.add((i % 2 == 0) ? "even" : "odd");
  }
  //end of oddEven()    
}

So, for parity, you need to check the value of i, not the parArray, and to assign a class name, I used classList, but you can use className, etc...


See it live here:

function oddEven() {
  var parArray = document.getElementsByTagName("p");

  for (var i = 0; i < parArray.length; i++) {
    parArray[i].classList.add((i % 2 == 0) ? "even" : "odd");
  }
  //end of oddEven()    
}

oddEven();
.odd {color: blue}
.even {color: green}
<p>paragraph</p>
<p>paragraph</p>
<p>paragraph</p>
<p>paragraph</p>
<p>paragraph</p>
Shomz
  • 37,421
  • 4
  • 57
  • 85
2
function oddEven() {
    var i, elements = document.getElementsByTagName("p");
    for(i = 0; i < elements.length; i += 1) {
       elements[i].className = i % 2 === 0 ? "even" : "odd";
    }
}

You can also do it directly with CSS without any JavaScript:

p:nth-child(even) {
    background: #00ff00;
}
p:nth-child(odd) {
    background: #ff0000;
}

This only works if the ps share a common parent though.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

Your function no have chances to work. You are selecting p elements properly, but getElementsByTagName returns an Array of p elements so by parArray=="even" you are trying to compare Array of objects with String. Look at my code below and compare with yours.

I recomend you reading Change an element's class with JavaScript

    function oddEven()
    {
        var parArray = document.getElementsByTagName("p");
        var pElement;
        var i;

        for (i = 0; i < parArray.length; i++)
        {
            pElement = parArray[i];
            pElement.className += (i % 2) ? 'odd' : 'even';
        }
    }
Community
  • 1
  • 1
Likeee
  • 11
  • 2