2017-05-23 7 views
0

似たような質問と回答がたくさんありますが、すべての解決策を試した後、私のコードに何が間違っているかわかりません。ここでjavascriptでclassNameがundefinedを返す

ここに私のコード

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

で最初にconsole.logに表示するものである:

[a.xclass1.xclass2.xclass3] 

それは右の要素ここ

が示したものです見つけたことを示していますログ:

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

そして3つ目は、これを返します。

undefined class4 

誰が、なぜclassName戻りundefinedを説明していただけますか?私は完全にあなたが要素ではない、実際の要素を含むオブジェクトの配列のためのクラスをコンソールしようとしているので、コードスニペットの下に未定義

リターンを参照してくださいここで

+2

は 'getElementsByClassName'を返します。 – Li357

+1

classListを見てください –

+0

@AndrewLiありがとうございました!私はちょうどそれを見つけた... 'x [0] .className + = 'class4';'それを修正する –

答えて

1

を失っています。要素のコレクションは*、1つだけでなく、あなたが同じクラスで複数の要素を持つことができますので、*

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>

関連する問題