Javascript |如何使用类名打印第二个元素

如何使用类名“ nameAnswer”打印第二个元素。 它说:undefined为什么?

HTML:

<h1 class="nameAnswer" value="dog"></h1>
<h1 class="nameAnswer" value="cat"></h1>
<h1 class="nameAnswer" value="fish"></h1>

JAVASCRIPT:

var count = document.getElementsByClassName("nameAnswer").length;
if(count>1){
var answ = document.getElementsByClassName('nameAnswer'[2]).value;
alert(answ);
}
评论
  • lenim
    lenim 回复

    尝试这个:

    const val = document.querySelector('.nameAnswer:nth-child(2)').getAttribute('value')
    
    console.log(val)
    <h1 class="nameAnswer" value="dog"></h1>
    <h1 class="nameAnswer" value="cat"></h1>
    <h1 class="nameAnswer" value="fish"></h1>
  • 一纸离人醉
    一纸离人醉 回复

    You need to put [2] after the parentheses. Or just do the following:

    var nameAnswers = document.getElementsByClassName("nameAnswer");
    var count = nameAnswers.length;
    if(count > 1){
        var answer = nameAnswers[2].value;
        alert(answer);
    }
    
  • tmodi
    tmodi 回复

    试试这个

    var count = document.getElementsByClassName("nameAnswer").length;
    if(count>1){
      var answ = count[2].value;
      alert(answ);
    }