Try   HackMD

8. createElement 寫法

更加安全且嚴謹的方式動態加入 HTML 語法:

  • 作法,首先先在 HTML 增加一個 h1.title:
// HTML:

<h1 class="title">
    
</h1>
  • CSS 撰寫一組 .blue:
// CSS:

.blue {
    color: blue;
    font-size: 24px;
}
  • JavaScript:

    createElement,動態新增一個元素
    setAttribute,動態設定str的屬性與值

// 新增一個宣告變數名稱: str,並增加標籤元素為: <em>
var str = document.createElement('em');

// 替 str 掛上一段文字:'富邦悍將'
str.textContent = '富邦悍將';

// 替 str 設定屬性,更動內容為'class','blue'
str.setAttribute('class','blue');

.appendChile,在元素之下掛載你動態新增的節點屬性

  • 預期這串文字的效果會吃到 css 的藍色以及大小為:24效果。

    上面已經完成了:新增 em 標籤、textContent、透過屬性設定吃樣式
    最後的步驟就是將設定好的 str 掛在你想要的節點上,也就是 .title

document.querySelector('.title').appendChild(str);

如果是透過 createElement 方式來動態新增元素,並不會像innerHTML 一樣直接刷新內容,而是乖乖的增加在最後面:

  • HTML:
<h1 class="title">
    <em>中信兄弟</em>
</h1>
  • 會發現我們所寫的 str 富邦悍將會乖乖跑到原本就在 HTML 的中信兄弟後方

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

tags: JavaScript - DOM 元素