accessing certain element in HTMLCollection

2019-08-17 04:53发布

问题:

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.

I have this block of code inside ngOnInit

window.addEventListener('load', function (){
      let tabcontent = document.getElementsByClassName('tab');
      console.log(tabcontent[0]); // <----- 
    })

and I have this in the view template

<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>

the console.log output undefined sometimes while other times give some HTML element. Any explanation of why document.getElementsByClassName gives undefined value sometimes!!

回答1:

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


回答2:

If you're using angular you should do things the angular way. Angular has an init event which you can call:

<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};

See this post: How to execute AngularJS controller function on page load?