Solve the problem that document.getElementBy series methods cannot obtain objects

Solve the problem that document.getElementBy series methods cannot obtain objects

getElementById cannot get the object

There is a sequence when the browser parses the document. Before the page is loaded, or before the corresponding DOM object is loaded, the corresponding object cannot be obtained.

Look at the following code:

<script>
    var temp = document.getElementById("div");
    alert(temp);
</script>
<body>
<div id="div">
    <input name="username" id="username" type="text">
    <button id="btn">Button</button>
</div>
</body>

In this code, document.getElementById(“div”) cannot get the object, and alert(temp) will pop up null;

This is because when the browser parses the code in the script tag, the DOM elements in the body have not yet been loaded, so naturally nothing can be retrieved.

Solution: Move the code in the script to after the body element.

<body>
<div id="div">
    <input name="username" id="username" type="text">
    <button id="btn">Button</button>
</div>
<script>
    var temp = document.getElementById("div");
    alert(temp);
</script>
</body>

Or add window.onload

<script>
window.onload = function(){
    var temp = document.getElementById("div");
    alert(temp);
    }
</script>

Summarize

The above is the editor's introduction to solving the problem that the document.getElementBy series methods cannot obtain objects. I hope it will be helpful to everyone. Thank you very much for your support of the 123WORDPRESS.COM website!

<<: 

>>:  HTML solves the problem of invalid table width setting

Recommend

Should I use UTF-8 or GB2312 encoding when building a website?

Often when we open foreign websites, garbled char...

Solve the problem of VScode configuration remote debugging Linux program

Let's take a look at the problem of VScode re...

How to use async and await in JS

Table of contents 1. async 2. await: 3. Comprehen...

MySQL 8.0.13 installation and configuration method graphic tutorial under win10

I would like to share the installation and config...

Detailed installation tutorial for MySQL zip archive version (5.7.19)

1. Download the zip archive version from the offi...

centos7.2 offline installation mysql5.7.18.tar.gz

Because of network isolation, MySQL cannot be ins...

Vue realizes adding watermark to uploaded pictures (upgraded version)

The vue project implements an upgraded version of...

MySQL 4G memory server configuration optimization

As the number of visits to the company's webs...

Introduction to Common XHTML Tags

<br />For some time, I found that many peopl...

Play mp3 or flash player code on the web page

Copy code The code is as follows: <object id=&...