getElementById returns null in JavaScript page building

32 views Asked by At

I created the structure in JavaScript. I do not use HTML. I have a function that creates the structure and returns the root pane.

function createEmptyChartPane (chartId) { 
  let divelem = document.createElement('div');
  let elem = document.createElement('textarea');

  elem.id = "chartdescr" + chartId;
  elem.rows = 6;
  elem.cols = 80;
  divelem.append(elem);

  // ...some other code, other elements

  return divelem
}

This function is called from another one. It loops through the elements and creates them. After calling the previous function it tries to set the value of the elements. But it fails as getElementById returns null.

function createChartPanels () {

  let pane = document.createElement("div");

  // ... some other code
  for (let i; i < charts.length; i++) {
    pane.append(createEmptyChartPane(charts[i].id));

    let elem = document.getElementById("chartdescr" + charts[i].id);  // this returns null
    elem.value = charts[i].description;

    // ... setting value to other elements
  }
  return pane
}

Apart from the value setting, the functions works fine and to the job and create the graphical elements.

What can I do to avoid the null value?

1

There are 1 answers

0
Barmar On

The problem is that you never appended pane to the document, so document.getElementById() can't find it.

But there's no need to call document.getElementById() in the first place, since createEmptyChartPane() returns the element. You can just assign that to the elem variable.

function createChartPanels () {

  let pane = document.createElement("div");

  // ... some other code
  for (let i; i < charts.length; i++) {
    let elem = createEmptyChartPane(charts[i].id)
    pane.append(elem);
    elem.value = charts[i].description;

    // ... setting value to other elements
  }
  return pane
}