Elements in this environment are nested inside containers - let's call them widgets. Given any element, I want to find its containing widget using a custom method called parentWidget. The widget can always be identified by the class name "widget". I want this to behave exactly like parentElement, except that it might be several levels deep, so it should use the JavaScript method .closest() to traverse up the DOM tree.
I wrote this, but I don't like that I need to use parenthesis to execute the function:
Element.prototype.parentWidget = function() {
return this.closest('.widget');
}
// Custom method
Element.prototype.parentWidget = function() {
return this.closest('.widget');
}
// Works
function test(el) {
var widget = el.parentWidget();
var result = document.getElementById("w1");
result.firstChild.innerText = widget;
}
/* This is a silly example to illustrate what I'm
* trying to achieve, except that I don't want to
* require parenthesis. Instead, I want this to
* seem like a native method like, 'parentNode' or
* 'firstChild'
*
* How can I rewrite this?
*/
:root {
--btn1: hsl(206, 100%, 52%);
--btn2: hsl(206, 100%, 40%);
}
.widget {
display: block;
top:10px;
left:10px;
height: 36px;
width: 150px;
}
.widget > div {
height: inherit;
width: inherit;
}
.style-1 button {
color: white;
background-color: var(--btn1);
border: none;
border-radius: 3px;
transition: background .25s;
}
.style-1 button:not([disabled]):hover {
background-color: var(--btn2);
}
.full {
height: 100%;
width:100%;
}
<div id="w1"><span>Click to test</span></div>
<div class="widget">
<div class="style-1">
<button type="button" class="full" onclick="test(this)">Try Me</button>
</div>
</div>
At some point, I may want to concatenate other methods, so I won't want to use parenthesis (e.g., el.parentWidget.firstChild, etc.)