0

A simple javascript file is running absolute fine, But when I try to insert those code in angular (from assets OR inserting code in index.html file) giving unexpected value.

HTML code
<p class='collect'> this is text </p>
<p class='collect'> this is text </p>
<p class='collect'> this is text </p>
//js in separate file

var all = document.getElementsByClassName('collect');
console.log(all.length);

//returns 3 
//js code in angular

var all = document.getElementsByClassName('collect');
console.log(all);

// returns 
HTMLCollection []
length: 3
0: p.collect
1: p.collect
2: p.collect 

// but in
console.log(all.length);
// returns 0

Amit Kumawat
  • 114
  • 1
  • 1
  • 12

3 Answers3

1

You should try document.querySelector('.collect').

Sohan
  • 558
  • 6
  • 17
0

I found this answer and I think you need to inject DOCUMENT in orden to work:

(I'm assuming you are using Angular and not AngularJS

import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(private document: DOCUMENT) {
      document.getElementsByClassName('collect');
      console.log(all.length);
   }
}

Let me know if that works for you.

Richard Fazzi
  • 433
  • 3
  • 9
  • I dont think injecting document is required.. OP can access the element using ElementRef , ViewChild or simply using queryselector – Amit Feb 24 '20 at 12:15
  • yes, of course, but this answer is if you need/want to use `document`. There are alternatives too as you said, @ViewChild being one. – Richard Fazzi Feb 24 '20 at 12:18
  • For using document, injection is not required. And you answer says I think you need to inject Document.. this might create confusion – Amit Feb 24 '20 at 12:22
0

length is coming zero because till the time Angular component which having these p tags, has not loaded in dom. So put this code inside lifecycle hook ngAfterViewChecked.

harsh_apache
  • 433
  • 4
  • 10
  • I think they are loaded because on console.log(all); // returns HTMLCollection [] length: 3 0: p.collect 1: p.collect 2: p.collect // but in console.log(all.length); // returns 0 – Amit Kumawat Feb 26 '20 at 07:26