P粉8271215582023-08-15 10:45:51
Demo refers to the paragraph with the id "demo". You can use an id (which must be unique throughout the HTML page) to identify and use html tags in javascript.
document.write is indeed no longer used very often. There are several reasons. Since there are good explanations on the web, check out these answers or this article.
If you add some missing tags like </head>
, <body>
and <script>
, your code will is working fine and console logging is happening. Run the code snippet below.
As a side note, best practice now is to do javascript processing and loading at the bottom of the page before closing the </body>
tag. Because any loading happens after the DOM is loaded.
function addNumbers(arr) { var i, answer = 0; for (i = 0; i < arr.length; i++) { answer += arr[i]; } return answer; } var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.getElementById("demo").innerHTML = addNumbers(myArray); console.log(addNumbers(myArray))
<html> <head> </head> <body> <h4> Function addNumbers: </h4> <p id="demo">This is a paragraph that can be identified using the id attribute.</p> </body> </html>
P粉7574324912023-08-15 09:16:35
One step back, two steps forward:
document.write
is one of the three functions
document.open()
Opens a document for writing from the beginning, deleting existing document content if any exists. document.write( string)
Inserts a string into the character stream used to build a web page. document.close()
Closes a document for writing. Further writing will reopen the document and clear existing content in the process. Now consider the following
document.open/write/close
Existed before the DOM was standardized and available. Therefore, document.write
has little use in modern web programming. If used after the page has finished loading, it clears the page content. It is almost entirely limited to tutorials for students who have not yet learned that the DOM exists, and occasional use when writing content programmatically in a child window opened with window.open
.
All HTML elements in the page exist as HTMLelement nodes in the DOM. These elements can be accessed by calling methods such as document.getElementById
or document.querySelector
, and returned as JavaScript object values. HTMLElement varies depending on the tag type, but if they represent an HTML container element, have attributes such as innerHTML
and textContent
, which when updated with a text string from a script, Changes the content of the rendered page.
To answer your question, "demo" is the id value of HTMLParagraphElement, where the id value is used to access a specific element in the DOM - the id
value should be unique among page HTMLElements of.
The (paragraph) element object can be obtained by querying the DOM using document.getElementById
. Subsequent changes to the element's innerHTML
content will cause the document to re-render with the new content, updating the page's display.