0

Let's say I have this paragraph:

<p id="paragraph">Hello World!</p>

I want to add "Hello StackOverflow! " at the start of the paragraph.

document.getElementById("paragraph").innerHTML += "Hello StackOverflow! "

Adding the above line didn't work as it adds the content to the end of the paragraph, not the start.

Is there a way to do this?

Thanks!

Rani Giterman
  • 708
  • 2
  • 6
  • 17

2 Answers2

0

You can use a template string to easily do this:

document.getElementById("paragraph").innerHTML = `Hello StackOverflow! ${document.getElementById("paragraph").innerHTML}`
<p id="paragraph">Hello World!</p>
Daniel
  • 1,392
  • 1
  • 5
  • 16
0

You can save the previews text in a variable and then update the innerHTML

const el = document.getElementById('paragraph')
const prevTxt = el.innerHTML

el.innerHTML = 'Hello StackOverflow! ' + prevTxt
<p id="paragraph">Hello World!</p>
Gass
  • 7,536
  • 3
  • 37
  • 41