我是靠谱客的博主 苗条煎饼,这篇文章主要介绍JavaScript如何判断节点是否存在,现在分享给大家,希望可以做个参考。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

前两天工作时遇到一问题,就是模块A显示时,B是一种样式,模块A删除,B是另一种样式。记录下判断节点存在的方法。

先写下html

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!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])

放到代码里

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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>
登录后复制
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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如何判断节点是否存在的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是苗条煎饼最近收集整理的关于JavaScript如何判断节点是否存在的全部内容,更多相关JavaScript如何判断节点是否存在内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部