Cannot read property 'style' of undefined — Uncaught Type Error

前端 未结 2 515
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 14:49

I would like to change the color, fontsize and font weight of the text in a span element of the html page.

I am using the following code:

if(window.locat         


        
相关标签:
2条回答
  • 2021-02-13 15:29

    It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

    window.onload = function() {
    
      if (window.location.href.indexOf("test") <= -1) {
        var search_span = document.getElementsByClassName("securitySearchQuery");
        search_span[0].style.color = "blue";
        search_span[0].style.fontWeight = "bold";
        search_span[0].style.fontSize = "40px";
    
      }
    
    }
    <h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>

    0 讨论(0)
  • 2021-02-13 15:37

    Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

    If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

    You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

    This works when you execute it in Dev Tools because the DOM is already loaded.

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