本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
前两天工作时遇到一问题,就是模块a显示时,b是一种样式,模块a删除,b是另一种样式。记录下判断节点存在的方法。
先写下html
<!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>
判断id为box1的p是否存在的方法
js方法
if(document.getelementbyid('box1'))
jquery方法
1.if($('#box1').length>0)
2.if($('#box1')[0])
放到代码里
<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方法
<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>
每天进步一点点,努力超越昨天的自己。
【推荐学习:javascript高级教程】
以上就是javascript如何判断节点是否存在的详细内容。
