Although is not completely clear what you want to accomplish, or more importantly why, this question intrigues me. The functionality you are trying to obtain reminds me of jQuery library, I think you should check that out.
What you describe is a function that returns an object in wich you can call methods and set properties. As far as I know there is no way to have an object with a property and a method with the same name, so you wont be able to do both: function().html = 'something'
and function().html('something')
.
Nevertheless similar behavior can be obtained with minimal changes by calling the method differently. For example prefixing the method with ‘set’, like: function().setHtml('something')
. Another thing that works is capitalization, as having a method named Html is different from a property html.
I’ve made an example query function that receives a selector parameter and allows to get and set the innerHtml and style of the element that corresponds to the given selector. The function returns an object where you can call setHtml() and setStyle(), also has html and style properties.
An example use of the function would be:
query('body')
.setHtml('Hi')
.setStyle({ "text-align": "center" });
As you can see the methods are chainable, because each method returns the same object so you can keep invoking methods. If you dont need to chain more methods or just want to get the value of the properties you can use for example:
query('body').html = 'Hello'; // to set
const someVar = query('body').html; // to get
This is just an example, to be useful the query function would have to be extended with methods to get and set other needed properties of html elements. If this is what you need then the answer is to look at jQuery or other libraries for DOM manipulation like React.
Finally, i’ll leave here the code of the query function in case the example’s link breaks some day.
query function
function query(selector) {
return {
element: document.querySelector(selector),
get html() {
return this.element.innerHTML;
},
set html(value) {
this.element.innerHTML = value;
},
setHtml(value) {
this.html = value;
return this;
},
get style() {
return this.element.style;
},
set style(properties) {
for (const [key, value] of Object.entries(properties)) {
this.element.style[key] = value;
}
},
setStyle(value) {
this.style = value;
return this;
}
};
}