简体   繁体   中英

How to add text to HTML element on web page using JavaScript DOM

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"

Try this

 function myFunction() { var h3 = document.getElementsByTagName('h3'); h3[0].innerText = "List of things we need to learn" }
 <body onload="myFunction()"> <h3>Some Text</h3> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM