如何检查元素ID是否在文档中?

时间:2017-10-08 16:17:42

标签: javascript jquery html css

我的网站提供动态内容,因此页眉和页脚保持不变。页脚是我的JS脚本,有一些document.getElementById('ids').addEventListener('click',function(e)。 当尚未提供具有元素ID的内容时,如何防止JS错误TypeError: document.getElementById(...) is null?请参阅以下示例JS代码:

    <script>
        // DN_1, 1st page Switch On/Off
        document.getElementById('dn_1_yes-no').addEventListener('click',function(e){
            var attrChk = document.getElementById('dn_1_yes-no'); 
            if( this.checked){
                document.getElementById('external_dn_1').style.display='block';
            }else{
                document.getElementById('external_dn_1').style.display='none';
            }
        });

        // DN_2, 2nd page Switch On/Off
        document.getElementById('dn_2_yes-no').addEventListener('click',function(e){
            var attrChk = document.getElementById('dn_2_yes-no'); 
            if( this.checked){
                document.getElementById('external_dn_2').style.display='block';
            }else{
                document.getElementById('external_dn_2').style.display='none';
            }
        });

        // more.....

    </script>

1 个答案:

答案 0 :(得分:0)

这有效!

    <script>
        var dn1Ele = document.getElementById('dn_1_yes-no');
        var dn2Ele = document.getElementById('dn_2_yes-no');

        if(dn1Ele != null) { 
            // DN_1 Switch On/Off
            document.getElementById('dn_1_yes-no').addEventListener('click',function(e){
                var attrChk = document.getElementById('dn_1_yes-no'); 
                if( this.checked){
                    document.getElementById('external_dn_1').style.display='block';
                }else{
                    document.getElementById('external_dn_1').style.display='none';
                }
            });
        }

        if(dn2Ele != null) { 
            // DN_2 Switch On/Off
            document.getElementById('dn_2_yes-no').addEventListener('click',function(e){
                var attrChk = document.getElementById('dn_2_yes-no'); 
                if( this.checked){
                    document.getElementById('external_dn_2').style.display='block';
                }else{
                    document.getElementById('external_dn_2').style.display='none';
                }
            });
        }

        // more.....

    </script>