简体   繁体   中英

passing this.id to another function returns null error

I am trying to pass an ID with a function to another function. The console then informs me that there is a TypeError: document.getElementById(...) is null . The javascript file is appended at the end and I also tried adding the code into a self executing function, but that didn't solve the problem.

Basically I would like to an addEventListener to the sub-category divs (buttons) and they should pass their value to another function.

The error is pointing at this line let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id); so recived_value is null .

Any help would be welcome. Thank you.

HTML:

<div class="wrapper">
   <div class="main-category" id="box">
      Boxes
   </div>
   <div class="sub-category" id="b_small">
      Small Boxes
   </div>
   <div class="sub-category" id="b_medium">
      Medium Boxes
   </div>
   <div class="sub-category" id="b_large">
      Large Boxes
   </div>
</div>

JS:

var subCategoryClass = document.querySelectorAll(".sub-category");
var subCategoryArray = Array.from(subCategoryClass);

for ( let i = 0; i < subCategoryArray.length; i++ ){
   subCategoryArray[i].addEventListener("click", PassValue(this.id));
}

function PassValue(recived_value){
   let subCategory = recived_value;
   let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id);
   TwoArgFunc(mainCategory, subCategory);
}

There were a couple of problems. I described them below in // comments.

Edit: Based on your comment, I changed to a normal function definition.

 var subCategoryClass = document.querySelectorAll(".sub-category"); var subCategoryArray = Array.from(subCategoryClass); for ( let i = 0; i < subCategoryArray.length; i++ ){ subCategoryArray[i].addEventListener("click", function(ev) { PassValue(ev.target.id)} ); // need a function here, not just a statement } function PassValue(recived_value){ console.log(recived_value); let subCategory = recived_value; let mainCategory = document.getElementById(recived_value).parentNode.firstElementChild.id; // use firstElementChild because firstChild is a newline text node console.log(mainCategory); // TwoArgFunc(mainCategory, subCategory); }
 <div class="wrapper"> <div class="main-category" id="box"> Boxes </div> <div class="sub-category" id="b_small"> Small Boxes </div> <div class="sub-category" id="b_medium"> Medium Boxes </div> <div class="sub-category" id="b_large"> Large Boxes </div> </div>

Above PassValue function put:

var that = this;

And then in your PassValue function pass that.id :

... .firstChild(that.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM