简体   繁体   中英

Adding className to specific array items in javascript

I'm trying to add a className to option elements in a select element using a conditional if statement so the first half of the array has one class name and the second half has a different class name. This conditional statement is in a for loop because I need to set the disabled value for every option element to 'true' on page load.

The loop runs, and the conditional runs, but the conditional sets the class names for every option in the array to the same class name. I am having a hard time finding a solution to this online so it's time I pose my own question.

Here's an example of my code. (Note: the array length is 6)

for (let i = 0; i < array.length; i++) {
  array[i].disabled = true;

  if (array[i] <= 2) {
    array[i].className = 'classOne';
  } else {
    array[i].className = 'classTwo';
  }
}

So, yeah, every option element gets the className of "classTwo". I'm having a rough go of it over here.

Thanks in advance!!!

I think you want to change:

if (array[i] <= 2) {

to

if (i <= 2) {

Since you're array items are objects and not numbers.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM