0

There are a lot of similar questions and answers, but after trying all solutions I can't figure out what's wrong with my code.

Here is my code

var x = document.getElementsByClassName('xclass1 xclass2 xclass3');
console.log(x);
x.className += ' class4';
console.log(x);
console.log(x.className);

Here is what shows up in the first console.log:

[a.xclass1.xclass2.xclass3]

It shows that it finds the right element

Here is what shows up in the second console.log:

[a.xclass1.xclass2.xclass3, className: "undefined class4"]

And the third one returns this:

undefined class4

Can anyone please explain why className returns undefined? I am completely lost here

Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57
  • 2
    `getElementsByClassName` returns *a collection of elements*, not just one, because you can have multiple elements with the same class. – Andrew Li May 23 '17 at 13:05
  • 1
    take a look at classList – Alexander_F May 23 '17 at 13:05
  • @AndrewLi Thank you very much! I just figured it out... `x[0].className += ' class4';` fixes it – Arthur Tarasov May 23 '17 at 13:06
  • If you are sure there will only be one such element on a certain page, you could just do var var x = document.getElementsByClassName('xclass1 xclass2 xclass3')[0]; and it should work – Ozgar May 23 '17 at 13:06
  • try to change this `x[0].className += ' class4';` to this `x[0].classList.push('class4');` now with classList you have directly an array of classes, no need of concatenating strings with className – quirimmo May 23 '17 at 13:08

1 Answers1

2

See below code snippet

return undefined because you trying to console class for array of object which include element not actual element.

var x = document.getElementsByClassName('xclass1 xclass2 xclass3');
console.log(x);
x[0].className += ' class4';
console.log(x);
console.log(x[0].className);
<div class="xclass1 xclass2 xclass3"></div>
sumit chauhan
  • 1,270
  • 1
  • 13
  • 18