getElementById is a method that returns an element with a specified id value as an Element object. You can use getElementById to obtain the specified ID from the HTML tag to process certain content. Let's take a closer look at how to use getElementById.
Usage of getElementById
The way to get the element using getElementById is as follows
document.getElementById(id)
Set the id you want The id element obtained in HTML. Since the same id cannot be used multiple times in HTML, it must be a unique id value.
If there are multiple ids in the HTML, only the first matching id element is returned. If the specified id does not exist, null is returned.
Let’s look at specific examples
Display characters
The code is as follows
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <p id="text"></p> <script> document.getElementById("text").innerHTML = "你好,php中文网!"; </script> </body> </html>
The running results are as follows
Display the connection text
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <p id="text2"></p> <script> document.getElementById("text2").innerHTML = "a" + "b"; </script> </body> </html>
The running results are as follows
Display calculation results
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <p id="text3"></p> <script> document.getElementById("text3").innerHTML = 3 + 5; </script> </body> </html>
The running results are as follows
##Finally, Since there are many uses of getElementById in DOM (Document Object Model), we need to master it as much as possible.The above is the detailed content of How to use getElementById in JavaScript. For more information, please follow other related articles on the PHP Chinese website!