Skip to content
Advertisement

Replacing text in an input box of a webpage (with defined ID)

I am trying to fill up all the input fields of a webpage (having input IDs ending with txtValue) which are filled with the word ‘dog’ to be replaced with the word ‘cat’. I have tried this code, but it isn’t working. Kindly help me to solve this. Thank you in advance.

const ta = document.querySelectorAll("[id$='txtValue']");

const str = ta.value.replace("dog","cat");
ta.value = str
console.log(ta.value,"change to" ,str)

Advertisement

Answer

querySelectorAll returns an array which needs to be iterated over.The replace method returns the modified string without changing the original.So,the following should work.

ta.forEach(elem => elem.value = elem.value.replace("dog","cat"))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement