Home > Software engineering >  Getting an error 'TypeError: Cannot read properties of undefined (reading 'setAttribute�
Getting an error 'TypeError: Cannot read properties of undefined (reading 'setAttribute�

Time:11-30

I am trying to set an attribute for the input tag webelement for the value but actually I am getting this below error

Below is the code which I have written for this,

'document.getElementsByName('date')[0].setAttribute('value','2022-11-29');'

and the below error is getting

enter image description here

Can some one help with this,

Thanks in Advance

CodePudding user response:

For me it seems that there is no element with the name "date" on the page.

Maybe you could also try document.getElementsByName("date")[0].value = "2022-11-29" ?

although i think the problem is with the selector itself

CodePudding user response:

It is clear from the error description that when

document.getElementsByName('date')[0].setAttribute('value','2022-11-29');

is executed there is no element with the name attribute === 'date'.

Try to execute

document.getElementsByName('date')

It should return NodeList which should contain necessary element (it is, presumably, empty which is the root of the error).

As stated in one of the answers, you could also modify the value of the element by:

document.getElementsByName("elementName")[0].value = 'newValue'

But be aware that it modifies the value of the element and not the value attribute of the element.

So, it's easy to console.dir that element and look that it has value property (which is changed by direct assignment to it) and attributes property which is NamedNodeMap object that contains the element's attributes (which properties are assigned by setAttribute method).

  • Related