找不到未定义的元素

时间:2017-09-04 00:50:04

标签: javascript html css

所以我一直得到这个问题“Uncaught TypeError:无法在HTMLInputElement.filterNames中读取未定义的属性'getElementsByTagName'”,但它已定义。我已经被这个困了40分钟了,我似乎无法弄清楚这一点。       https://jsfiddle.net/0bhepryk/1/

// Get input element
var filterInput = document.getElementById("filterInput");
// Add event listener
filterInput.addEventListener("keyup", filterNames);

function filterNames(){
  //Get value of input                                  //This make is upper cased.
  var filterValue = document.getElementById("filterInput").value.toUpperCase();
  //Get Names ul
  var ul = document.getElementById("names");
  //Get lis from ul
  var li = ul.querySelectorAll("li.list-group-item");
  //Loop through list-group-items
  for(var i = 0; i < li.length; i++){
    var a = li[i].getElementsByTagName("a")[0];
    //If matched  //a.innerHTML grabs whats inside the a tag, which is the names.
    if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

1 个答案:

答案 0 :(得分:0)

如果a未定义,则应该处理。为什么?因为<li>不包含<a>,所以.getElementsByTagName()会返回未找到元素的空数组,[0]未定义。

let a = li[i].getElementsByTagName("a")[0];

if (a)
{
  //If matched  //a.innerHTML grabs whats inside the a tag, which is the names.
  if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
    li[i].style.display = "";
  } else {
    li[i].style.display = "none";
  }
}

希望有所帮助