HTML - DOM value 屬性



HTML DOM 的value屬性用於設定或獲取屬性的值。您可以使用此屬性訪問各種屬性的值,例如表單中的“input”值、“img”中的“src”或連結中的“href”。

此屬性主要用於表單處理和DOM操作。

語法

以下是 HTML DOM 的value(獲取屬性值)屬性的語法:

attribute.value

要更新(設定)屬性值,請使用以下語法:

attribute.value = new_value

其中,new_value 指定您要分配給 value 屬性的新值。

引數

由於它是一個屬性,所以它不接受任何引數。

返回值

該屬性返回指定索引的屬性的值。

示例 1:獲取第一個屬性的值

以下是 HTML DOM value屬性的基本示例:

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM value</title>
</head>
<body>
<p>The value property of DOM returns the value of an attribute.</p>
<div id="demo" data-info="someData"></div>
<script>
   const element = document.getElementById("demo");
   // Retrieve the value of the first attribute of the div
   let attributeValue = element.attributes[0].value;
   // Place the value inside the div tag
   document.getElementById("demo").innerHTML = attributeValue;
</script>
</body>
</html>

示例 2:獲取所有屬性的值

這是 HTML DOM value屬性的另一個示例。在此示例中,簡單的 for 迴圈與 value 屬性一起使用,以檢索 HTML 元素的所有屬性的值:

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM value</title>
</head>
<body>
<h3>HTML DOM Attribute value Property</h3>
<p>The value property of DOM returns the values of attributes.</p>
<div id="demo" class="exampleClass" data-info="someData"></div>
<script>
   const element = document.getElementById("demo");
   // Initialize an empty array to hold attribute values
   let attributeValues = []; 
   // Loop through all attributes of the element
   for (let i = 0; i < element.attributes.length; i++) {
      attributeValues.push(element.attributes[i].value);
   }
   // Join the attribute values with commas 
   // and place them inside the div tag
   document.getElementById("demo").innerHTML = attributeValues.join(", ");
</script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
value
廣告