Benjamin W Benjamin W - 5 days ago 6
Javascript Question

pass a paramenter into object and use it for querySelector but return null

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?

Answer

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>

Comments