更改getElementsByClassName的样式会导致编译错误

3
我正在尝试更改通过调用getElementsByClassName方法获取的所有元素的样式。问题是,它只有在之前编译过(我将这些行注释掉以便进行编译)时才起作用,它只是在cmd中显示错误。编译后,我将这些行设置回正常状态,它们仍然会产生错误,但在浏览器中可以正常工作。对于这种奇怪的行为有什么想法吗?

enter image description here

enter image description here

当被注释掉时:

enter image description here

当未被注释且出现错误时:

enter image description here


你能使用jQuery吗? - לבני מלכה
我会使用jQuery,但我更倾向于不这样做。如果我找不到其他解决方案,我将使用jQuery表示法。 - BrianM
4个回答

6
我认为问题出在TypeScript上。你应该尝试这个解决方法。
var texts = document.getElementsByClassName("section_text") as HTMLCollectionOf<HTMLElement>;

很遗憾,我无法使用HTMLElement标签,因为该集合是<HTMLCollectionOf<Element>>类型的。这可能是TypeScript的问题。 - BrianM
这样做就可以了,谢谢!现在编译时不会出现任何错误。 - BrianM

0

你可以简单地使用addClass()

CSS

.newStyle{
    width:100%;
    float:left;
}

使用Jquery

$('.section_text input').addClass('newStyle');

使用Javascript

document.querySelector('.section_text input').classList.add('newStyle';

以下是使用JS添加类的方法:https://www.w3schools.com/howto/howto_js_add_class.asp - לבני מלכה

0

getElementsByClassName 返回一个节点列表。可以直接访问属性。

let hiddenLocales = document.getElementsByClassName('localeMatch') as HTMLCollectionOf<HTMLElement>;
let hideParentNode = hiddenLocales[0].parentElement;
hideParentNode?.classList.add('newStyle');

enter image description here


0

我之前在尝试使用Angular时遇到了类似的问题。问题在于getElementsByClassName返回的是节点列表,而不是普通数组,因此您无法像尝试的那样访问属性。您可以在这个回答中了解更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接