-1
var ajaxFileUploader = function(formId){
    this.formId = formId;

    console.log(this.formId); //myForm
    return console.log(
        document.querySelector(this.formId)// null
    );
}

var foo = new ajaxFileUploader('#myFrom');

I try to create a object and pass a parameter into it.

it works fine when I console.log this property

but when I try to use querySelector, it return null

anyone know why it return null?

Benjamin W
  • 2,658
  • 7
  • 26
  • 48

2 Answers2

0

enclose the whole code within window.onload=function(){}. you might have placed the script in head but the elements are at body thats why element loads late and script returns null. if you use window.onload=function(){} the script will run after the whole document once loaded

window.onload=function(){
var ajaxFileUploader = function(formId){
    this.formId = formId;

    console.log(this.formId); //myForm
    return console.log(document.querySelector(this.formId));
}

var foo = new ajaxFileUploader('#myFrom');
  }
<form id="myFrom" action="demo_form.asp" method="get">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>
jafarbtech
  • 6,842
  • 1
  • 36
  • 55
0

There is an issue with respect to context get lost of 'this'

Solution 1:

var ajaxFileUploader = function(formId){
    this.formId = formId;
    console.log(this.formId); 
    var logger = console.log.bind(this);
   return logger(
       document.querySelector(this.formId)
   );
}

var foo = new ajaxFileUploader('#myFrom');

Solution 2:

Another solution is you can use "formId" which will get by lexical context of function.

Vijayraj
  • 193
  • 1
  • 5