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

How to construct a table index in MySQL

Table of contents Supports multiple types of filt...

Use of Linux telnet command

1. Introduction The telnet command is used to log...

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which me...

Tips for designing photo preview navigation on web pages

<br />Navigation does not just refer to the ...

MySQL million-level data paging query optimization solution

When there are tens of thousands of records in th...

How to start a Java program in docker

Create a simple Spring boot web project Use the i...

HTML+CSS div solution when relative width and absolute width conflict

Div solution when relative width and absolute wid...

Mysql 5.6 "implicit conversion" causes index failure and inaccurate data

background When performing a SQL query, I tried t...

How to use react-color to implement the front-end color picker

background We can use react-color to implement th...

Example of how to deploy MySQL 8.0 using Docker

1. Refer to the official website to install docke...

Batch replace part of the data of a field in Mysql (recommended)

Batch replace part of the data of a field in MYSQ...