Delving into the implementation details of a JavaScript library has always been an enjoyable experience. A group of us were emulating the $(“#id”).val() method provided by jQuery. jQuery provides a val() function on input elements. A val() function returns the value of the input element and a val(“value”) sets the value of the input element.
function $(expression) { if (expression.indexOf("#") != -1) { var id = expression.split("#")[1]; return document.getElementById(id); } } HTMLInputElement.prototype.val = function (text) { if (text) this.value = text; else return this.value; } //You can use it as $("#idOfTheElement").val("hello");
The $ method resolves the expression “#id” and returns the DOM object associated with the id. You can wire up a val function using “prototype” keyword on the HtmlInputElement class.