How to handle getElementById return Null

后端 未结 4 1304
感动是毒
感动是毒 2021-01-27 13:22

On our web application there are many pages. Some of them contain element \"Ribbon.ListForm.Display.Manage.Workflows-Medium\" while some pages not.

I would like to use s

相关标签:
4条回答
  • 2021-01-27 14:08

    Since the question is tagged with jQuery:

    $('#Ribbon\.ListForm\.Display\.Manage,#Ribbon\.ListForm\.Display\.Manage\.Workflows-Medium,#Ribbon\.ListForm\.Display\.Manage\.CheckOut-Large')
        .filter(function() {
            return this.value == '';
        })
        .hide();
    

    First, it will select the elements you're interested in; then, it will hide those that match a simple filter based on value.

    0 讨论(0)
  • 2021-01-27 14:14

    You can check like this for null element:

    if (edit!=null && edit.value == '') 
    if (wf!=null && wf.value == '')
    if (checkout!=null && checkout.value == '')
    
    0 讨论(0)
  • 2021-01-27 14:24

    Because getElementById() returns null if the element is not found.

    element is a reference to an Element object, or null if an element with the specified ID is not in the document.

    You can just check for the truthy value instead of use the typeof test

    if (edit && edit.value == ''){edit.style.display = "none";};
    

    Demo: Fiddle

    0 讨论(0)
  • 2021-01-27 14:24

    Even if the element is not existing in the page, the return type will be object and return value will be null. so, you can check the null case also. please see the modified code.

    function hideEdit() {
        var edit = document.getElementById("Ribbon.ListForm.Display.Manage");
        if ( edit != null && typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";};
        var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium");
        if (wf != null && typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";}
        var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large");
        if (checkout != null && typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";}
    

    }

    thanks, varun.

    0 讨论(0)
提交回复
热议问题