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

How to determine whether a div exists in javascript

青灯夜游
青灯夜游Original
2021-12-06 14:57:335208browse

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>

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!

Statement:
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