0)" and "if($(' Element object ')[0])"."/> 0)" and "if($(' Element object ')[0])".">
Home > Article > Web Front-end > How to determine whether a node exists in JavaScript
Method: 1. js method, "if(document.getElementById('Element Object'))"; 2. jquery method, "if($('Element Object').length>0)" and "if($('Element Object')[0])".

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
I encountered a problem when I was working two days ago. When module A is displayed, B is one style. If module A is deleted, B is another style. Record the method to determine the existence of the node.
Write the html first
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge chrome=1" />
<meta name="keyword" content="随机加判断存在" />
<meta name="description" content="" />
<title>判断节点存在</title>
<style type="text/css">
*{margin: 0;padding: 0;}
#box1{width: 100px;height: 100px;background: #c66;margin: 20px auto;text-align: center;color: #fff;line-height: 100px;}
.box2{width: 200px;height: 200px;background: #c60;margin: 0 auto;text-align: center;color: #fff;line-height: 200px;}
.box22{width: 400px;height: 400px;line-height: 400px;}
</style>
</head>
<body>
<div class="box2">模块二</div>
<div id="box1">模块一</div>
</body>
</html>Method to determine whether p with the id of box1 exists
js method
if(document.getElementById('box1' ))
jquery method
1.if($('#box1').length>0)
2.if($('#box1')[ 0])
Put it in the code
<script type="text/javascript">
var number = (1+Math.random()*(8-1)).toFixed(0);
var oBox2=document.getElementsByTagName('div')[0];
var oBox1=document.getElementById('box1');
if(number<3){
document.body.removeChild(oBox1);
}
if(document.getElementById('box1')){
oBox2.className=oBox2.className+' box22';
console.log(111);
}
else{
oBox2.className='box2';
}
</script>jquery method
<script src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var number = (1+Math.random()*(8-1)).toFixed(0);
if(number>3){
}
else{
$('#box1').remove();
}
if($('#box1').length>0){//判断
$('.box2').addClass('box22');
}
else{
$('.box2').removeClass('box22');
}
</script><script src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var number = (1+Math.random()*(8-1)).toFixed(0);
if(number>3){
}
else{
$('#box1').remove();
}
if($('#box1')[0]){//判断
$('.box2').addClass('box22');
}
else{
$('.box2').removeClass('box22');
}
</script>Make a little progress every day and strive to surpass yourself yesterday.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine whether a node exists in JavaScript. For more information, please follow other related articles on the PHP Chinese website!