访问HTMLCollection中的某些元素 [英] accessing certain element in HTMLCollection
问题描述
我正在尝试在有角度的组件中使用 document.getElementsByClassName
,但有时会得到意外的值. document.getElementsByClassName
有时会给出一个值(HTML元素),而其他时候是 undefined
.
I am trying to use document.getElementsByClassName
in an angular component but sometimes I get unexpected value. document.getElementsByClassName
sometimes give a value (HTML element) and other times is undefined
.
我在 ngOnInit
window.addEventListener('load', function (){
let tabcontent = document.getElementsByClassName('tab');
console.log(tabcontent[0]); // <-----
})
我在视图模板中有这个
<div id='parent_div_2'>
<div *ngFor="let collection of collections; let i=index">
<!--targeted element -->
<div class="tab tab{{i}}" *ngIf="collection != null">
<table class="table table-borderless">
<tbody>
<tr *ngFor="let each of collection.collApps; let i = index">
<td>
<img *ngIf="imageLoaded && this.imageToShow[i]" [src]="this.imageToShow[i]"
style="width:30%;" alt="Place image title">
</td>
<td> <h4>{{each.name}}</h4></td>
<td> <form #form action="http://{{each.link}}">
<input type="submit" value="Launch" (click)="form.submit()"/>
</form> </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
console.log
输出 undefined
有时有时会给出一些HTML元素.为什么 document.getElementsByClassName
有时会给出 undefined
值的任何解释!
the console.log
output undefined
sometimes while other times give some HTML element. Any explanation of why document.getElementsByClassName
gives undefined
value sometimes!!
推荐答案
我不确定,但这可能是因为页面正在加载并且元素和您尝试访问的元素仍未定义.尝试使用此...
I'm not sure, but maybe is because the page is loading and the elements and the one you're trying to access is still undefined. Try to use this...
window.addEventListener('DOMContentLoaded', (event) => {
// do something
});
这篇关于访问HTMLCollection中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!