Avascript is often used to manipulate HTML and change Web content!
Output content to a page
JavaScript provides a document.write (' string ') method to write content to a page:
<!DOCTYPE HTML><HTMLLang= "en"xmlns= "http://www.w3.org/1999/xhtml"><Head> <MetaCharSet= "Utf-8" /> <title>Test for changing HTML content using JavaScript-take-off network</title> <Scripttype= "Text/javascript">document.write ("I am from JS content ~"); functionWritehtmllater () {document.write ("haha, I have covered the content ~"); } </Script></Head><Body> <H1>Test for changing HTML content using JavaScript-take-off network</H1> <P><inputtype= "button"value= "Click to overwrite all content"onclick= "Writehtmllater ()" /></P></Body></HTML>
You can copy this code into an HTML file and run it, and when the page runs in the browser, the effect
This time we click on the button and you will notice that all the content on the page is overwritten:
The "culprit" that overrides the page content is the Writehtmllater method called by the button onclick event, which also writes a word to the page, but overwrites the entire page, which needs to be noted:
document.write () only writes to the document, and if document.write is executed after the document has finished loading, the entire HTML page will be overwritten.
Change the contents of HTML tags
We use JS not only to output some content to the document, but also to change the display of existing labels. A way to access document tags is provided in javascript: the document.getElementById () method, which allows us to get the HTML tags we want to manipulate and change their display:
<!DOCTYPE HTML><HTMLLang= "en"xmlns= "http://www.w3.org/1999/xhtml"><Head> <MetaCharSet= "Utf-8" /> <title>Test for changing HTML content using JavaScript-take-off network</title> <Scripttype= "Text/javascript"> functionchangemyspanhtml () {document.getElementById ("MySpan"). InnerHTML= "I was changed by JS after the content"; } </Script></Head><Body> <H1>Test for changing HTML content using JavaScript-take-off network</H1> <P>Span content:<spanID= "MySpan">I am the original content of the span tag!</span></P> <P><inputtype= "button"value= "Click to change span content"onclick= "changemyspanhtml ()" /></P></Body></HTML>
Running this code, you will see the following page content:
When we click the Change span content button, you will notice that the content of the span tag has changed:
This is because we get the tag in the code and re-assign the value to its innerHTML property.
Use JavaScript to change HTML content