如何访问 document.getElementsByTagName 中的元素

How to access the elements in document.getElementsByTagName

大家好,节日快乐。我希望你们都保持温暖和安全。我在这里是因为我对某些代码有一点问题。我不是编程新手,但对 JavaScript 相当陌生。我已经搜索了这个问题的答案并在这个网站上找到了它,但即使在实施商定的解决方案之后我似乎还是遇到了问题。抛出的 TypeError 指向首次使用 'var sections' 变量的行。该行只是将 h1 元素附加到 NodeList 中带有“class="section"”的当前 div。 TypeError 数据显示 'cannot read property appendChild of null',这意味着我没有对 Element 类型节点的正确引用,我需要它才能使用 appendChild() 或样式 object。我只是想弄清楚这有什么问题,但只是不知所措。我在另一个线程上得到的关于如何使用 getElementsByClassName() 正确获取元素引用的答案说,您只需使用 NodeList object 的 'item()' 方法,如下所示:

var sections = document.getElementsByClassName('section');
var section_header = document.createElement('h1');
sections.item(0).appendChild(section_header);

对比我最初使用的是什么...

var sections = document.getElementsByClassName('section');
var section_header = document.createElement('h1');
sections[0].appendChild(section_header);

... 在我切换到 'NodeList.item()' 方法后,我开始收到 TypeError。所附图片是 chrome 开发工具的屏幕截图,sublime 的一个实例,您在文本编辑器中看到的打开页面是您在 chrome 中看到的打开页面(深色背景的空白页面)。我这样做只是为了学习,所以它不是为了一个项目或任何东西。它只是便笺本代码。我希望此 post 符合论坛政策,因为我知道可以使用商定的答案,但如您所见,仍然存在问题。感谢大家的宝贵时间和提前提出的建议,非常感谢。

这是我实际使用的测试代码,在 sublime 中打开的屏幕截图中可以看到。只是扔在那里,我确实尝试移动脚本标签本身(例如在头部,在 body 开始和 body 结束标签上方,但错误仍然存​​在:

<html>
    <head>
        ...
    </head>
    <body>
        <div id="page-wrapper">
            <div class="section">

            </div>
            <div class="section">

            </div>
            <div class="section">

            </div>
        </div>
        <script type="text/javascript">
            // Colors to be applied to each sections background.
            var colors = ['#455a64','#616161','#5d4037'];

            // The sections.
            var sections = document.getElementsByClassName('section');

            // The header tag to add to each section.
            var section_header = document.createElement('h1');

            // The count to be added to each sections title ex. <h1>Section Title #1.</h1>
            var section_count = 1;

            for(var index = 0; index <= colors.length; index++) {
                // The text to be added to each sections header.
                var section_header_txt = 'Section #' + section_count;
                // Add the text with the incremented section count to the sections h1 element.
                section_header.innerHTML = section_header_txt;
                // Append the section header to its new section parent.
                sections.item(index).appendChild(section_header); // This is where the TypeError is thrown. 
                // Add styles to each new section.
                sections.item(index).style.backgroundColor = colors[index].toString();
                sections.item(index).style.width = '100%';
                sections.item(index).style.height = '100vh';
                // Raise the section title count by 1.
                section_count++;
            }
        </script>
    </body>
</html>

screenshot of workspace

更新:

按照下面的建议,我将大小写运算符从 <= 更改为 < 但无济于事。我仍然收到相同的 TypeError: cannot read 属性 'appendChild' of type null。这是更新和结果的屏幕截图:

enter image description here

丹的回答更新:

下面是建议的更改结果的屏幕截图。我仍然收到此错误。

enter image description here

好吧,我去掉了一堆代码,现在它可以工作了。与 header 元素创建和附加有关的任何内容都消失了,但我看不出有什么区别。任何人都可以通过查看这个告诉我为什么它现在可以工作。奇怪的是,即使应用了背景颜色,我仍然收到 TypeError 说它无法读取样式 属性?!?!

Updated screenshot

你的 for 循环不好。 "for(var index = 0; index <= colors.length; index++)"
你有 3 个颜色项目,所以你的索引应该只在索引小于 colors.length.
时增加 因此,您需要在 for 循环中检查索引 < colors.length。
见下文。

        for(var index = 0; index < colors.length; index++) {
            // The text to be added to each sections header.
            var section_header_txt = 'Section #' + section_count;
            // Add the text with the incremented section count to the sections h1 element.
            section_header.innerHTML = section_header_txt;
            // Append the section header to its new section parent.
            sections.item(index).appendChild(section_header); // This is where the TypeError is thrown. 
            // Add styles to each new section.
            sections.item(index).style.backgroundColor = colors[index].toString();
            sections.item(index).style.width = '100%';
            sections.item(index).style.height = '100vh';
            // Raise the section title count by 1.
            section_count++;
        }

for 循环中,根据条件从 <= 更改为 <,因此它只循环 3 次而不是 4 次。在 4º 循环中,它尝试使用方法 appendChild在不存在的第 4 节(项目索引 4)上,创建错误。

// Colors to be applied to each sections background.
var colors = ['#455a64','#616161','#5d4037'];

// The sections.
var sections = document.getElementsByClassName('section');

// The header tag to add to each section.
var section_header = document.createElement('h1');

// The count to be added to each sections title ex. <h1>Section Title #1.</h1>
var section_count = 1;

for(var index = 0; index < colors.length; index++) {
  // The text to be added to each sections header.
  var section_header_txt = 'Section #' + section_count;
  // Add the text with the incremented section count to the sections h1 element.
  section_header.innerHTML = section_header_txt;
  // Append the section header to its new section parent.
  sections.item(index).appendChild(section_header); // This is where the TypeError is thrown. 
  // Add styles to each new section.
  sections.item(index).style.backgroundColor = colors[index].toString();
  sections.item(index).style.width = '100%';
  sections.item(index).style.height = '100vh';
  // Raise the section title count by 1.
  section_count++;
}
<div id="page-wrapper">
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
</div>

类型错误是由不正确的for循环condition引起的。 <= 4 将在索引 4 上执行 for 循环,这将 return undefined 用于 colors 数组。

您发布的代码还有其他问题。

  1. section_header 元素创建应移至 for 循环内。否则,您将重写同一元素的 html 并将其移动到最后一部分,结果只有第三部分具有 header 文本部分。
  2. GetElementsByClassname returns 元素数组。您可以简单地使用数组索引来引用元素,不需要 .item
  3. 您已经可以访问一个索引变量,只需将其加 1 而不是手动递增的 sectionCount 变量。

var colors = ['#455a64','#616161','#5d4037'];

// var sections is an array of  elements with 'section' as classname
var sections = document.getElementsByClassName('section');

for(var index = 0; index < colors.length; index++) {
  var section_header_txt = 'Section #' + ( index + 1 );
  
  // create a new section header element for each section
  var section_header = document.createElement('h1');
  section_header.innerHTML = section_header_txt;
  
  // instead of calling .item, just use array index
  sections[index].appendChild(section_header); 
  sections[index].style.backgroundColor = colors[index].toString();
  sections[index].style.height = '100vh';
}
<div id="page-wrapper">
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
</div>

谢谢大家,答案是简单地重新安排 Dan 发布的一些台词。 1) 我把 document.createElement('h1') 放在 for 循环的内部而不是上面。 2) 我切换到 document.createTextNode() 而不是使用 Element.innerHTML。 3) 至于使用 document.getElementsByClassName('section')[0]document.getElementsByClassName('section').item(0),我发现两者都有效并产生相同的结果。

正如您在屏幕截图中看到的那样,代码现在可以正常工作,但奇怪的是(至少对我而言)在控制台中我仍然收到相同的 TypeError 提示无法读取样式对象。

View of current work results

View of the sources view of the error