跳轉到內容

JavaScript/修改元素

來自華夏公益教科書,開放書籍,開放世界



在本頁中,我們展示如何更改 HTML 元素,即 DOM 節點的兩個不同方面。

  • 它的內容(只有一個,或者沒有)
  • 它的任何屬性(可能有很多)

請注意內容和屬性之間的這種區別。

<!-- in general: -->
<element_name attribute_name="attribute_value">content of the element</element_name>
<!-- a concrete example. 'href' is an attribute. 'Visit IANA...' is the content. -->
<a href="https://www.example.com">Visit IANA's example domain.</a>

示例頁面

[編輯 | 編輯原始碼]

我們使用以下示例 HTML 頁面來演示各種可能性。

<!DOCTYPE html>
<html>
<head>
  <script>
    function show() {
      "use strict";
      // ...
    }
  </script>
</head>

<body id="body" style="margin:2em">
  <p id="p1" style="background: aqua">A blue paragraph</p>

  <svg id="svgSrc" width="100" height="100" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="25" fill="green"/>
  </svg>

  <p />
  <a id="refToSomewhere" href="https://www.example.com">Visit IANA's example domain.</a>

  <p />
  <button id="buttonShow" onclick="show()">Start</button>
</body>
</html>

點選button會呼叫函式show。示例應包含在其中。

更改內容

[編輯 | 編輯原始碼]

我們以一個段落p為例。要更改它的內容(文字),只需將新值賦給它的innerHTML

function show() {
  "use strict";
  const elem = document.getElementById("p1");
  elem.innerHTML = "New text in the paragraph.";
}

或者,為了用不同的 HTML 元素做同樣的事情,我們更改 SVG 圖形。

function show() {
  "use strict";
  const elem = document.getElementById("svgSrc");
  elem.innerHTML = "<rect width='80' height='40' fill='blue'/>";
}

因為新文字是 HTML 程式碼,所以您可以“誤用”這種方法新增子節點。

function show() {
  "use strict";
  const elem = document.getElementById("p1");
  elem.innerHTML = "New text in the paragraph.<p>next P</p><p>and even one more P</p>";
}

指令碼插入了兩個額外的段落,但不在第一個段落之後。它們位於第一個段落中。

<p id="p1">New text in the paragraph
  <p>next P</p>
  <p>and even one more P</p>
</p>

更改屬性

[編輯 | 編輯原始碼]

通常,更改屬性的語法如下:

element_name.attribute_name = "new value";
// or:
element_name.setAttribute("attribute_name", "new value");

HTML 元素a有一個href屬性:<a id="refToSomewhere" href="https://www.example.com">...</a>。這個href屬性可以被修改。

function show() {
  "use strict";
  const elem = document.getElementById("refToSomewhere");
  elem.href = "https://wikibook.tw";
  elem.innerHTML = "Link changed";
}

首先,找到該元素。其次,該函式為其屬性“href”(和innerHTML)分配一個新值。

以下示例更改了img元素的src屬性和button元素的value屬性。

// The HTML
<img id="imgOne" src="myPicture.jpg">
<input id="buttonOne" value="I'm a button!">

// The JavaScript
document.getElementById("imgOne").src = "otherPicture.jpg";
const b = document.getElementById("buttonOne");
b.value = "I'm a changed button";

setAttribute()

[編輯 | 編輯原始碼]

也可以透過setAttribute函式修改屬性。

function show() {
  "use strict";
  const elem = document.getElementById("refToSomewhere");
  elem.setAttribute("href", "https://wikibook.tw");
  elem.innerHTML = "Link changed";
}
...在另一個頁面上提供(點選這裡)。
華夏公益教科書