Home > Web Front-end > JS Tutorial > How to determine whether a div exists in javascript

How to determine whether a div exists in javascript

青灯夜游
Release: 2021-12-06 14:57:33
Original
5327 people have browsed it

Judgment method: 1. Use the "document.getElementById("id value")" statement to obtain the div element object according to the specified id value; 2. Use the if statement to determine whether the div exists. The syntax "if (div element object ){//Element exists}else{//Element does not exist}".

How to determine whether a div exists in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

js determines whether the div element exists

In the native js’s getElementById() and getElementsByTagName() methods When operating elements, if the element being operated does not exist, the browser will throw an error and terminate the running of the code. Therefore, in order to avoid this situation, when it is impossible to determine whether the element to be operated exists, you can use the following Code to determine whether the element exists.

Implementation code

<div id="div">div元素</div>
<p>这是一个段落。</p>
<script>
	var div=document.getElementById("div");
	if (div){
		//元素存在的操作代码
		console.log("div元素存在");
	}else{
		//元素不存在的操作代码
		console.log("div元素不存在");
	}
</script>
Copy after login

How to determine whether a div exists in javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to determine whether a div exists in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template