难以通过document.body作为函数中的参数[重复]

问题描述 投票:0回答:1

我使用以下函数使用Javascript设置DOM元素:

  createDomEl(type, parentEl, id) {
    let el = document.createElement(type);
    parentEl.appendChild(el);
    el.id = id;

    return el;
    }

它工作得很好,除非我尝试将DOM元素附加到document.body。我尝试过几种方式传递body元素,包括:

const body_el = document.body;

要么

const body_el = document.getElementsByTagName('body')[0];

createDomEl('section', body_el, 'main-section');

但我得到了TypeError: parentEl.appendChild is not a function

编辑:我已将脚本标记移动到正文内部,如下所示:

<!DOCTYPE html>
<html>
<head>
 ...
</head>
<body>
 <script src="build/bundle.js"></script>
</body>
</html>

我可以在调用此函数之前记录body元素,即

console.log(body_el)

这个日志:

<body>...</body>

我也可以在函数中直接用document.body替换parentEl,函数也可以。问题似乎正在传递。

createDomEl函数在一个类中导入到一个主类中,从中作为实例的方法调用它,如下所示:

import CreateDomEls from './helpers/createDomEls.js';

class Layout {
  constructor(config) {
    this.createDomEls = new CreateDomEls();
    this.createMainSection();
  }

  createMainSection() {
    const body_el = document.getElementsByTagName('body')[0];
    console.log(body_el);
    const mainSection = this.createDomEls.createDomEl(
      'section',
      body_el,
      'main-survival-game-station'
    );
  }
javascript dom
1个回答
0
投票

您的脚本标记位于结束</body>标记之外(下方)。脚本标记必须位于<body></body><head></head>块内才能运行。如果它在文档(<html></html>)级别,它将被忽略。

<script>标记移动到正文的末尾,这样就可以保证在脚本执行时加载了正文。

<body>
  ...
  <script>
    // this will run once the body has loaded
  </script>
</body>

此外,您可以将脚本保留在头部并监听文档加载事件。这些天你通常可以依靠

window.onload = function() {
  // your code which manipulates the document here
  createDomEl('section', body_el, 'main-section')
}

请注意,只有执行DOM操作的代码才需要进入window.onload事件处理程序。函数本身可以存在于此处理程序之外。

© www.soinside.com 2019 - 2024. All rights reserved.