-2

I want to change my list background but it wont work

my code :

change(num, element){
var text

if (num == 1){ ... }
else if (num == 2) { ... }
else { ... }

document.getElementById('text').innerHTML = text;

document.getElementByClass("left").style.backgroundColor = "black"; //<------ 
element.style.backgroundColor = "white";                            //<------
}

and my html :

<ul>
   <li><a class="left" href="#" onclick="change(1,this)>First</a></li>
   <li><a class="left" href="#" onclick="change(2,this)>Second</a></li>
   <li><a class="left" href="#" onclick="change(3,this)>Third</a></li>      
</ul>

When i click on one of my list element , the text changes but background color won't ...

How i can fix this ?

Thanks,

Al00X
  • 1,492
  • 1
  • 12
  • 17
  • 1
    Open your browser's developer tools. Look at the console. Read the error messages. Call a function that actually exists! Then look at the duplicate question for your second problem. – Quentin Jul 12 '16 at 12:10
  • correct: document.getElementsByClassName(), (it returns array) You are using document.getElementByClassName() (s missing) – Dinesh Patra Jul 12 '16 at 12:11
  • @DineshPatra — getElementsByClassName doesn't return an array, just something that is like an array in some ways. – Quentin Jul 12 '16 at 12:12
  • @Quentin, in the console (in this page) as there is a element with class name 'default', I tried this typeof(document.getElementsByClassName('default')); it is returning object, But I need to access innerHTML by document.getElementsByClassName('default')[0].innerHTML; So i think its array' Also as per https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName it says array like object – Dinesh Patra Jul 12 '16 at 12:16
  • @DineshPatra — If you try `document.getElementsByClassName('default') instanceof Array` then you'll see that it is not an array. If you try `document.getElementsByClassName('default').forEach(...)` then it will error, but all arrays have a `forEach` method. It does not return an array. – Quentin Jul 12 '16 at 12:18
  • @DineshPatra — It says "array like object" and not "array" because it is not an array. – Quentin Jul 12 '16 at 12:18
  • @Quentin thank you for ur clarification. As per it's usage, I thought its array. But frankly I had only once used this. Otherwise I use document.querySelector(); – Dinesh Patra Jul 12 '16 at 12:20

1 Answers1

0

There's no such function as getElementByClass, there's only getElementsByClassName, wich returns an array. You need to choose the one you want to change out of this array or use ids

Bálint
  • 4,009
  • 2
  • 16
  • 27