Having some trouble selecting class names with plain ‘ol vanilla javascript:
var email = document.getElementsByClassName('email');
var phone = document.getElementsByClassName('phone');
// Hide phone by default
phone.style.display = "none";
function showContact() {
var dropdown = document.getElementById( "contact-select" ); // Get a reference to the dropdown (select) element
var selectedItemValue = dropdown.options[ dropdown.selectedIndex ].value; // use the dropdown reference to get the selected item's value
if ( selectedItemValue === "phone" ) {
email.style.display = "none";
phone.style.display = "block";
} else {
phone.style.display = "none";
email.style.display = "block";
}
}
Keep getting an undefined error anytime I try to call one of the variables. Any help would be greatly appreciated. Thanks!
Hint:
document.getElementsByClassName— Notice that is plural. It returns annodeListor anull.First step of debugging should have been a
console.log(phone)and see what value it did have.Without seeing your markup, I have to take some guesses but try:
Edit: Returns a
nodeListwhich is array-like, but not actually an array.