0

I have the following JS function which should change the word "hi" to "yo" on a button click if the user has input this. For example "hi, how are you today?" ==> "Yo, how are you today?"

function changeWord() {
  let str = document.getElementById('inputBox').innerHTML;
  document.getElementById('inputBox').innerHTML = str.replace("hi", "yo");;
}

The above doesn't work when I call changeWord(); on click, any ideas?

2
  • input box is a textbox? What is the HTML markup? If it is an textbox, it has a value, not innerHTML. Commented Oct 5, 2021 at 18:39
  • 1
    And just like my comments to your other question. A regular expression with word boundaries is probably a better idea. Commented Oct 5, 2021 at 19:00

2 Answers 2

2

You should be targeting the value of the input rather than the HTML.

const input = document.querySelector('input');
const button = document.querySelector('button');
button.addEventListener('click', changeWord, false);

function changeWord() {
  const str = input.value;
  input.value = str.replace("hi", "yo");
}
<input type="text" />
<button>Click</button>

Sign up to request clarification or add additional context in comments.

2 Comments

A word of caution to OP .. The way you are perceiving your str.replace -- "hi" will definately be replaced with "yo" -- BUT "him" will also become "yom" and "this" will become "tyos". Conversely the way this is written. "I said hi, and she said hi back" will only change the first instance .. returning "I said yo, and she said hi back"
I agree @Zak, but this answers the question. A more robust solution would probably involve regex which might be out of the OP's wheelhouse.
1

Use .value instead of .innerHTML, like this:

let str = document.getElementById('inputBox').value;
document.getElementById('inputBox').value = str.replace("hi", "yo");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.