I need to add text to an element on the web page using only JavaScript (just started learning about DOM in my JS class). It is an h3 element, with the HTML code:
<h3>List of things we need to learn</h3>
I need to change this to say "List of things we need to learn about JavaScript" when I load the page using only JavaScript. I've tried several different methods and none of them seem to work. One of the examples is:
var h3Add = document.getElementsByTagName('h3');
document.h3Add.insertAdjacentHTML("beforeend", ' about JavaScript');
I used the code above, along with many others and am very frustrated. I think I can solve this by deleting the current h3 element and creating a new h3 element, but would rather do something more direct.
TYIA
There are a few issues with your code.
document.getElementsByTagName()
returns an htmlCollection
object, not a DOM element. An htmlCollection
can be addressed like an array, so if your h3 is the first h3 on the page, you should write:
var h3Add = document.getElementsByTagName('h3')[0];
To access the content of the h3 you should use the .innerText
field, which acts like a string.
To add the text " about javascript" we would write: `h3Add.innerText += " about javascript"