简体   繁体   English

Javascript 未按 ID 找到 DOM 元素

[英]Javascript not finding DOM element by ID

I have a div on my page:我的页面上有一个 div:

<div id="report"></div>

I'm trying to convert a filtered array to nested ULs within that div using this:我正在尝试使用以下方法将过滤后的数组转换为该 div 中的嵌套 UL:

  let arr = csvData.filter(row => unchecked.includes(row[0]))
  
  console.log(arr);
  
  const div = document.getElementById("report");
  
  const prepareUL = (root, arr) => {
   let ul = document.createElement('ul');
   let li;
   root?.appendChild(document.createElement('ul'));
   arr.forEach(function(item) {
      if (Array.isArray(item)) {
         prepareUL(li, item);
         return;
      };
      li = document.createElement('li');
      li.appendChild(document.createTextNode(item));
      ul.appendChild(li);
   });
}

  
  prepareUL(div, arr);

If I do not check for the existence of the root, I get an error reading appendchild of undefined.如果我不检查根是否存在,读取未定义的 appendchild 时会出错。 I am running the javascript deferred.我正在运行延迟的 javascript。 The array logs properly to the console.阵列正确记录到控制台。 Weirdly, if I just:奇怪的是,如果我只是:

div.innerHTML = arr;

UPDATE: if I change the array to a simple assigned array, like:更新:如果我将数组更改为一个简单的分配数组,例如:

const arr = [
   'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'],
   'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'
];

It also works.它也有效。

it populates the div with the (unformatted) array.它用(未格式化的)数组填充 div。 So why would the innerHTML not have an issue finding the element, but the above function cannot?那么为什么innerHTML在查找元素时没有问题,而上面的function却不行呢?

Help is much appreciated.非常感谢您的帮助。

Inside your forEach you call在你的forEach你调用

prepareUL(li, item);

At that point, li is undefined , thus inside prepareUL(root, arr) root will be undefined .此时, liundefined ,因此在prepareUL(root, arr) root内部将是undefined

As connexo pointed out li is undefined when you recursively call prepareUL function.正如 connexo 指出的那样,当您递归调用prepareUL function 时, li是未定义的。 So creating li before calling prepareUL is probably the right thing to do.因此,在调用prepareUL之前创建li可能是正确的做法。

 let arr = ['url', 'url1', ['url2', 'url3', 'url4']] const div = document.getElementById("report"); const prepareUL = (root, arr) => { let ul = document.createElement('ul'); root.appendChild(ul); arr.forEach(function(item) { let li = document.createElement('li'); if (Array.isArray(item)) { prepareUL(li, item); ul.appendChild(li); return }; li.appendChild(document.createTextNode(item)); ul.appendChild(li); }); } prepareUL(div, arr);
 <div id="report"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM