How to replace jQuery .val() function in javascript es6?

Viewed 356

I am assigning a value to an element like the following.

$(element).val('abc');

I want to do the same in javascript es6. I tried with the following code but it is not working.

document.querySelector(element).value = 'abc';

How can I do this?

1 Answers

If element is already a DOM element, then you would just use:

element.value = 'abc'`

And, of course, this assumes it's the type of HTML element that has a .value property such as an <input> element. If it's not, then we have to know what type of HTML element you are targeting.

You would only use document.querySelector(element) if element was a CSS selector string such as "#submitbutton" or "#myform .password" or some other form of CSS selector string that targets the desired element in the page. If you show your actual HTML, we can help with how to target it with a CSS selector (if that's what you're trying to do).

Related