getElementsByClassName Help (Uncaught reference error when assigning to variable)

前端 未结 3 1287
说谎
说谎 2021-01-22 06:16

Having some trouble selecting class names with plain \'ol vanilla javascript:

var email = document.getElementsByClassName(\'email\');
var phone = document.getEle         


        
3条回答
  •  有刺的猬
    2021-01-22 07:10

    1. If you are doing this in an older version of IE getElementsByClassName is not defined so your email and phone variables are undefined.
    2. If this is added to the page before the elements phone and email are loaded then email and phone will be undefined.
    3. getElementsByClassName return a node list so you should actually define email and phone.

    Code:

    var email = document.getElementsByClassName('email')[0];
    var phone = document.getElementsByClassName('phone')[0];
    

    Update: Or loop through the array:

    for(var i = 0; i < phone.length; i++)
    {
        phone[i].style.display = "none";
    }
    

提交回复
热议问题