JavaScript/Changing elements

維基教科書,自由的教學讀本

在 JavaScript 中,您可以使用以下語法更改元素:

element.attribute="new value"

在這裡,圖像的src 屬性發生了變化,因此當調用腳本時,它將圖片從 myPicture.jpg 更改為 otherPicture.jpg:

//The HTML
<img id="example" src="myPicture.jpg">
//The JavaScript
document.getElementById("example").src="otherPicture.jpg";

為了改變一個元素,你可以使用它的參數名作為你想要改變的值。 例如,假設我們有一個按鈕,我們希望更改它的值。

<input type="button" id="myButton" value="I'm a button!">

稍後在頁面中,使用 JavaScript,我們可以執行以下操作來更改該按鈕的值:

myButton = document.getElementById("myButton"); //searches for and detects the input element from the 'myButton' id
myButton.value = "I'm a changed button"; //changes the value

要更改輸入的類型(例如,將按鈕更改為文本),請使用:

myButton.type = "text"; //changes the input type from 'button' to 'text'.

另一種更改或創建屬性的方法是使用 element.setAttribute("attribute", "value")element.createAttribute("attribute", "value")。 使用 setAttribute 更改之前已定義的屬性。

//The HTML
<div id="div2"></div> //Make a div with an id of div2 (we also could have made it with JavaScript)
//The Javascript
var e = document.getElementById("div2"); //Get the element
e.setAttribute("id", "div3"); //Change id to div3

但是,如果您想設置一個以前沒有定義過的值,請使用 createAttribute()

var e = document.createElement('div'); //Make a div element (we also could have made it with HTML)
e.createAttribute("id", "myDiv"); //Set the id to "myDiv"