文約 1 分鐘閱讀
Javascript使用setAttribute更改HTML元素屬性方法
分類文
標籤#javascript
Javascript可以使用getElementsById setAttribute來做到跟改html元素屬性方法如下:
範例一
document.getElementsById("images").setAttribute("width", "200");
//執行結果 <img id="images" src="" width="200"></code></pre>
<h2>範例二</h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
Click the button to add a class attribute with the value of "democlass" to the h1 element.
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementsByTagName("H1")[0].setAttribute("class", "democlass");
}
相關連結展示:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_setattribute1