❤ cannot read properties of null(reading appendChild) solution

❤ Operation element report: cannot read properties of null (reading appendChild) solution

1. Scene:

I wrote a js rendering, but there was a small problem. Cannot read properties of null (reading appendChild) reported an error.

<div id="divps" class="divps"></div>

The rough meaning is: Empty attributes cannot be read.

Insert image description here

2. Solution

1. console.log() //Print the data content and check whether there is any problem in obtaining the data.

2. The js introduction is placed at the end of the body. The page runs from top to bottom, and the HTML is not run. Of course, the corresponding node cannot be obtained.

3. When using getElementsByClassName(''div") to obtain elements, it returns an array instead of locating a specific object.

There is also the getElementsByTagName() method. The getElementsByTagName() method returns an HTMLCollection object. The HTMLCollection object is similar to an array containing HTML elements. It may look like an array, but it is not. However, like an array, you can use an index to obtain elements.

3、后期添加

In many later operations, Array.form() in ES6 can also convert this type of array into an array;

Therefore, when using this method to obtain elements, you only need to locate a specific element and let the browser know which element to add child nodes under.

Change as follows:

document.getElementsByClassName(“divps”)[0];

Or just get the ID

document.getElementById(“divps”);

Guess you like

Origin blog.csdn.net/weixin_43615570/article/details/130729909