JavaScript如何判断节点是否存在

文章2023-01-3064 人已阅来源:网络

方法:1、js方法,“if(document.getElementById('元素对象'))”;2、jquery方法,“if($('元素对象').length>0)”和“if($('元素对象')[0])”。

JavaScript如何判断节点是否存在

本教程操作环境: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如何判断节点是否存在的详细内容!