Make .val act like .value

How do I make .val act like .value? So

document.getElementById("input").val

would act like

document.getElementById("input").value

Thanks.

JS isn’t exactly my strong suit but (and someone correct me if I’m wrong) I don’t think that you can.

Not in pure vanilla JS, that is.

You’d have to use jQuery to be able to use .val

$('#input').val()

would be the jQuery equivalent of

document.getElementById("input").value

jQuery is a JS library, which makes the code more concise and somewhat easier to use (personal opinion). But you’d have to learn how to use it, as it differs from plain vanilla JS.

If jQuery can do it with JS, isn’t it possible?

Doubt it, besides, is it to get the same result only with two less characters?

If you want your code to be more concise, why not simply use jQuery? :slight_smile:

Or am I missing something?

I was going to use for other things too. I’ll just research a little more. Thanks though.

jQuery doesn’t meet my needs. I need

document.querySelector("#input").val = "something"

.value is a native property. It is created by the browser itself, not you or your program.

jQuery just creates a function that gets value.

If you make it a function though, you will still have to type the parenthesis which makes it just as long as value
Both value and val() are 5 characters.

The one way I can think of doing it while being as close to your example as possible is this:

Object.defineProperty(HTMLInputElement.prototype, "val", {
  enumerable:true,
  configurable:true,
  get: function(){
    return this.value;
  }
});

However, it is bad practice to edit the DOM and it is quite hacky (it will only work for elements created with document.createElement after you define the getter).

In reality I don’t think you really do need to make your own “val” property as value is just fine.

I also see you want to change the value.

document.querySelector("#input").val = "something"

would literally be the same as

document.querySelector("#input").value = "something"

Yes, HTMLInputElement.prototype.value is editable :slight_smile: