当元素及其类名是动态创建的(例如document.createElement)时,如何将div放入文档中



我有以下方法,主要目的是:

  1. 能够创建多个div,所有div都具有不同的类
  2. 使用这些,我们为多个图表创建"容器">

问题是这个方法动态地创建了div和类。我需要在文档中提供它们才能真正使用appendChild,但由于它们是动态创建的,我无法将它们硬编码到文档中

我已经在必要的地方发表了评论,以显示线条的用途。

createChartContainer(chartRef) {
// bring up the grid object
for (var chartDataInTable of this.tableData) {
// if this grid does not have 0 charts
if(chartDataInTable.summary_charts.length != 0) {
// create div
var createDiv = document.createElement('div');
// generate a string I can use as the class name for the newly created div shown above
var randomStringAsClassNames = Math.random().toString(36).substring(7);
// assign the random string as the className for the newly created div
createDiv.className = 'div_' + randomStringAsClassNames;
// chartClassName is defined as a string in data: () => ....
this.chartClassName = createDiv.className;
// non-negotiable as this shows the details of the created chart
var eChart = chartRef.chartElement;
// select the div that we've just created
var eParent = document.querySelector("." + this.chartClassName + "");
eParent.appendChild(eChart);
}
}
},
STRUCTURE OF ELEMENTS IN <script> TAG i.e. the Document (Note: I'm using Vue JS) (e.g. where the div should go)
<template>
<v-card>
<v-text-field
label="Please enter chart name"
v-model="chartName"
append-outer-icon="mdi-content-save"
@click:append-outer="saveChart"
/>
</v-card>
<template>

console.log(ePparent(返回null,并且出现以下错误:Uncaught TypeError:无法读取null 的属性"appendChild">

我之前收到的答案是,我需要把它放在文档中,但当我不知道类名是什么时,我该如何把一个新的、动态创建的div和一个新创建的类名放在文档里呢?

eParent需要是存在的DOM Element。例如,您可以调用document.querySelector('body')并获取body,然后可以将其附加到body元素。

在没有看到HTML结构的情况下,很难给您一个直接的解决方案。但简而言之,要附加到的父元素需要位于querySelector函数内部。

最新更新