JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

前端 未结 6 1778
北海茫月
北海茫月 2020-12-09 14:56

In short: I am trying to understand the meaning of this TypeError: Failed to execute \'getComputedStyle\' on \'Window\': parameter 1 is not of type \'Element\' The error app

6条回答
  •  北海茫月
    2020-12-09 15:33

    The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

    The most common case is that you try to pass an element that doesn't exist as an argument:

    my_element = document.querySelector(#non_existing_id);
    

    Now that element is null, this will result in mentioned error:

    my_style = window.getComputedStyle(my_element);
    

    If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

    if (my_element === null) return;
    

提交回复
热议问题