iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
自我挑戰組

開始入坑網頁吧!系列 第 28

JavaScript DOM | createElement()

接續昨天的 DOM 方法,JavaScript 常會出現:按一下某按鈕,頁面上會生出新的區塊,這是怎麼做到的?

用 createElement() 建立DOM 元素

JavaScript 可以在 DOM 中添加 一個原本沒有寫在 HTML 中的元素,要怎麼建立這個元素呢?
這時我們可以使用 Document Object 的方法 ~ createElement() 。
語法:document.createElement(節點名稱)

EX:

<!DOCTYPE html>
<html>
<body>


<script>
//建立button物件賦予給變數a
  var a = document.createElement("button");
//文字內容是"I'm button"
a.textContent="I'm button";
//把a物件添加在網頁body上
document.body.appendChild(a);
</script>

</body>
</html>

注意,createElement 節點是用字串形式當參數。

innerHTML 與 innerText 差別

innerHTML 是 此元素裡面包裹的 HTML 架構; innerText 是此元素裡面包的文字

<! DOCTYPE html>
<html>
<body>
<button onclick="CC()">click!! 大字</button>
<button onclick="DD()">click!! 小字</button>
<script>
function CC() {
  var btn = document.createElement("button");
  btn.innerHTML = "<h1>CLICK ME</h1>";//btn 會是 <button><h1>CLICK ME</h1></button>
  document.body.appendChild(btn);
}
function DD() {
  var btn = document.createElement("button");
  btn.innerText = "<h1>CLICK ME</h1>";//btn 會是 <button><h1>CLICK ME</h1></button>
  document.body.appendChild(btn);
}
</script>
</body>

</html>

下面是先按 click!! 小字 再按 click!! 大字
https://ithelp.ithome.com.tw/upload/images/20211013/20135414wBh4WWrc5z.png
參考文章:
tutorialspoint HTML DOM createElement() method


上一篇
JavaScript Document Object
下一篇
JavaScript DOM classList
系列文
開始入坑網頁吧!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言