Home > Article > Web Front-end > How to determine whether a div exists in javascript
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}".
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>
[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!