无法读取未定义的属性“样式”-未捕获的类型错误 [英] Cannot read property 'style' of undefined -- Uncaught Type Error

查看:95
本文介绍了无法读取未定义的属性“样式”-未捕获的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在html页面的span元素中更改文本的颜色,字体大小和字体粗细。

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

我正在使用以下代码:

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";
}

以下是我的html页面的代码

Following is the code for my html page

<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>

我想到了按id获取元素,但不幸的是,它们仅分类而没有id。我无权更改html代码,而只是在外部将js代码添加到网站。

I thought of getting elements by id but unfortunately they only classes and no ids. I do not have access to change the html code but just to add js code to website externally.

我尝试查看其他stackoverflow帖子,但可以找到解决方案。
是js和CSS的新手,请告诉我哪里出了问题。

I have tried to look into other stackoverflow posts but could find the solution. Am new to js and css,Please let me know where am going wrong.

推荐答案

< script> 添加到< body> ,或在DOMContentLoaded 添加事件侦听器>这个StackOverflow问题。

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

如果该脚本在代码的< head> 部分中执行,则文档.getElementsByClassName(...)将返回一个空数组,因为尚未加载DOM。

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.

由于引用 search_span [0],因此出现类型错误 ,但 search_span [0] 未定义

由于已加载DOM,因此在Dev Tools中执行时可以使用。

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

这篇关于无法读取未定义的属性“样式”-未捕获的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆