Lesson 2: The Document Object Model
Update Existing Page Content
1. Update an Element's Inner HTML
顯示某個element底下的html
The .innerHTML
property sets or returns the HTML content inside the selected element (i.e. between the tags).
There's also the rarely used .outerHTML
property. .outerHTML
represents the HTML element itself, as well as its children.
更新innerHTML
2. Update an Element's Text Content
So .innerHTML
will get/set an element's HTML content. If we just want the text content, we can use the fantastically named .textContent
property!
The .textContent
property will:
set the text content of an element and all its descendants
return the text content of an element and all its descendants
Check out the .textContent
's documentation page on MDN: textContent docs
更新內容:
textContent會把內容當作plain text輸出,而innerHTML則會parse內文的html tag。
3. An Element's Text Content - Version 2!
.innerText
will get the visible text of the element. If CSS is used to hide any text inside that element, .innerText
will not return that text, while .textContent
will return it.
innerText顯示apply css之後的文字,而textContent則回傳apply css之前的文字。
Add New Page Content
之前為修改現有element,現在為新增element。
1. Adding Content To The Page
As you've already discovered, the .createElement()
method is a method on the document
object:
https://developer.mozilla.org/en-US/docs/Web/API/Document
https://developer.mozilla.org/en-US/docs/Web/API/Node
https://developer.mozilla.org/en-US/docs/Web/API/Element
createElement只是建立新增的element,針對想要新增的element target呼叫appendChild才會新增element上去:
.appendChild() Needs An Element!
This is stated above, but I wanted to call this out, specifically. When you're using the .appendChild()
method, it must be called on an existing element. To be clear, you can't call this on the document
object, so the following will result in an error:
2. Creating Text Nodes
第二種方式則是產生內文後,再添加到element,多一個步驟:
creates a paragraph element
creates a text node
appends the text node to the paragraph
appends the paragraph to the tag
用以下的方式產生一樣的結果:
如果將同一個element多次appendChild給不同element,則只會append到最後一個指定的element。
3. Inserting HTML In Other Locations
問題:appendChild只能插入parent的child的最後一個位置。
解法:.insertAdjacentHTML()
Enter the .insertAdjacentHTML()
method! The .insertAdjacentHTML()
method has to be called with two arguments:
the location of the HTML
the HTML text that is going to be inserted
The first argument to this method will let us insert the new HTML in one of four different locations
beforebegin
– inserts the HTML text as a previous siblingafterbegin
– inserts the HTML text as the first childbeforeend
– inserts the HTML text as the last childafterend
– inserts the HTML text as a following sibling
Last updated