I have created simple web components using vanilla javascript as per the
The problem is on my hideNonVisibleDivs() i want to access shadowRoot
Here are my functions.
var visibleDivId = null;
var i, divId, div;
console.log('shadowroot', this); // display the global shadow root element
function divVisibility(divId) {
hideNonVisibleDivs.bind(this)(divId); //binding this context
}
function hideNonVisibleDivs(divId) {
//I want to access a shadow root here using this
console.log('shadowroot', this); //undefined
}
var panels = this.shadowRoot.querySelectorAll("#tab-info> .share-tab")
panels.forEach(function(el) {
divVisibility.bind(this)(this.getAttribute('custom-id')); //bind this context
});
});
What is Expected?
Inside hideNonVisibleDivs(divId) I want to access the shadowRoot as that of out side function (the global shadowroot ) meaning this.
The simplest solution I can offer is to stop using this.
The meaning of this changes with every function call, which is why you are having trouble understanding what it refers to at any point in your code.
For example, your divVisibility() function cannot work.
console.log( 'shadowroot', this ); //{this} is a shadowroot
//...
function divVisibility(divId) {
//shadow root {this} cannot be accessed at all from here
hideNonVisibleDivs.bind(this)(divId); //binding this context
//^Refers to divVisibility
}
Try rewriting your code without using this anywhere. Instead, use a variable name, such as 'shadowroot'. (Without knowing your code, I do not know how useful this advice is, unfortunately.)